Python日志记录-禁用导入模块的日志记录 [英] Python Logging - Disable logging from imported modules

查看:228
本文介绍了Python日志记录-禁用导入模块的日志记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python日志记录模块,并想禁用由我导入的第三方模块打印的日志消息.例如,我正在使用类似以下的内容:

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)

这在我执行logger.debug("my message!")时打印出我的调试消息,但是它也从我导入的任何模块(例如请求和许多其他东西)中打印出调试消息.

我只想查看我感兴趣的模块中的日志消息.是否可以使日志记录模块执行此操作?

理想情况下,我希望能够告诉记录器打印来自"ModuleX,ModuleY"的消息,而忽略所有其他消息.

我看了以下内容,但是我不想在每次调用导入函数之前都禁用/启用日志记录: 日志记录-如何忽略导入的模块日志?

解决方案

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

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

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

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


显然,您必须使用logger.debug而不是logging.debug,因为后者是调用根记录程序的debug方法的便捷功能.

高级日志记录中已提及.它还使您能够以简单的方式知道哪个模块触发了日志消息.

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?

解决方案

The problem is that calling getLogger without arguments returns the root logger so when you set the level to logging.DEBUG you are also setting the level for other modules that use that logger.

You can solve this by simply not using the root logger. To do this just pass a name as argument, for example the name of your module:

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

this will create a new logger and thus it wont inadvertently change logging level for other modules.


Obviously you have to use logger.debug instead of logging.debug since the latter is a convenience function that calls the debug method of the root logger.

This is mentioned in the Advanced Logging Tutorial. It also allows you to know which module triggered the log message in a simple way.

这篇关于Python日志记录-禁用导入模块的日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆