繁体   English   中英

Python:特定类的记录器的setLevel

[英]Python: setLevel of specific class's logger

如何在不知道班级记录员姓名的情况下使班级的记录静音? 有问题的课程是qualysconnect

import logging
import qualysconnect.util

# Set log options. This is my attempt to silence it.
logger_qc = logging.getLogger('qualysconnect')
logger_qc.setLevel(logging.ERROR)
# Define a Handler which writes WARNING messages or higher to the sys.stderr
logger_console = logging.StreamHandler()
logger_console.setLevel(logging.ERROR)
# Set a format which is simpler for console use.
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# Tell the handler to use this format.
logger_console.setFormatter(formatter)
# Add the handler to the root logger
logging.getLogger('').addHandler(logger_console)

# 'application' code
logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

注释掉import qualysconnect.util时的输出:

root        : ERROR    error message
root        : CRITICAL critical message

import qualysconnect.util保留在以下位置时的输出:

WARNING:root:warn message
ERROR:root:error message
root        : ERROR    error message
CRITICAL:root:critical message
root        : CRITICAL critical message

遗憾的是,由于他们没有为其记录器定义名称,并且像在qualysconnect.util一样,它们甚至都没有进行getLogger调用或getChild调用,因此您无法在不会影响整个模块的日志记录行为的方式上进行任何操作不弄脏。

我能想到的唯一干净的方法是报告他们将日志记录为错误的方式,并提交一个补丁请求,您可以在其中修改qualysconnect.util日志记录语句,如下所示:

import logging
logger = logging.getLogger('qualysconnect').getChild('util')

并将所有logging.info()logging.debug() ...替换为logger.info()logger.info() logger.debug() ...

肮脏的选项:您可以猴子修补qualysconnect.util模块,以便将其logging对象替换为logger对象:

import qualysconnect.util
logger_qc = logging.getLogger('qualysconnect')
logger_qc.setLevel(logging.ERROR)
qualysconnect.util.logging = logger_qc.getLogger('qualysconnect').getChild('util')
qualysconnect.util.logging.disable(logging.CRITICAL) # will disable all logging for CRITICAL and below

在向上游项目发送补丁程序请求时,这可能是一个有效的解决方案,但肯定不是长期有效的解决方案。

或者,您可以简单地关闭整个qualysconnect模块中的所有注销,但是我认为这不是您想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM