Python Logging - 禁用导入模块的日志记录

标签 python logging

I'm using the Python logging module, and would like to disable log messages printed by the third party modules that I import. For example, I'm using something like the following:

logger = logging.getLogger()
logger.setLevel(level=logging.DEBUG)
fh = logging.StreamHandler()
fh_formatter = logging.Formatter('%(asctime)s %(levelname)s %(lineno)d:%(filename)s(%(process)d) - %(message)s')
fh.setFormatter(fh_formatter)
logger.addHandler(fh)

This prints out my debug messages when I do a logger.debug("my message!"), but it also prints out the debug messages from any module I import (such as requests, and a number of other things).

I'd like to see only the log messages from modules I'm interested in. Is it possible to make the logging module do this?

Ideally, I'd like to be able tell the logger to print messages from "ModuleX, ModuleY"and ignore all others.

I looked at the following, but I don't want to have to disable/enable logging before every call to an imported function: logging - how to ignore imported module logs?

最佳答案

问题是调用 getLogger不带参数返回 root 记录器,因此当您将级别设置为 logging.DEBUG 时,您也在为使用该记录器的其他模块设置级别。

您可以通过简单地使用根记录器来解决这个问题。为此,只需传递一个名称作为参数,例如您的模块的名称:

logger = logging.getLogger('my_module_name')
# as before

这将创建一个新的记录器,因此它不会无意中更改其他模块的记录级别。


显然你必须使用 logger.debug 而不是 logging.debug 因为后者是一个调用 debug 方法的便捷函数根记录器。

这在 Advanced Logging Tutorial 中有所提及.它还可以让您以简单的方式知道是哪个模块触发了日志消息。

关于Python Logging - 禁用导入模块的日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35325042/

相关文章:

Python Pandas - 将多列合并为一列交错列

python - SynapsePay 和 Django 用户问题的冲突实例

python - 将计数器列表保存到 python 中的文件中

python - 如何使用多个打印参数将打印重定向到日志记录?

apache - 强制 Apache 更新日志文件路径,无需在 WAMP 中重新启动

python - 如何正确导入单元测试的相对路径

python - Moses v1.0 多语言ini文件

logging - 我可以使用 Web.config 配置 IIS 7 日志记录吗?

Linux tail 使用 busybox 旋转日志文件

python - 为什么无法在 Windows 上清除临时目录中我的文件处理程序的文件?