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/