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

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

问题描述

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

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)

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

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?

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

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 时还为使用该记录器的其他模块设置级别.

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.

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

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天全站免登陆