Python:特定类的logg的setLevel

2024-10-01 04:51:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在不知道日志记录器名称的情况下使类的日志保持沉默?有问题的类是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

Tags: thetoimportmessageloggingutilerrorroot
1条回答
网友
1楼 · 发布于 2024-10-01 04:51:17

遗憾的是,由于他们没有为他们的记录器定义一个名称,并且在qualysconnect.util中,他们甚至没有执行getLogger调用或getChild调用,因此您不能在一个不会影响整个模块的日志行为的日志上执行某些操作,而不会弄脏。你知道吗

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

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

替换所有logging.info()logging.debug()。。。变成logger.info()logger.debug()。。。你知道吗

脏选项:您可以对qualysconnect.util模块进行monkey修补,以便用logger对象替换其logging对象:

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模块的所有登录,但我认为这不是您想要的。你知道吗

相关问题 更多 >