如何在不知道日志记录器名称的情况下使类的日志记录静默?有问题的类是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
发布于 2013-06-21 15:22:49
遗憾的是,由于他们没有为记录器定义名称,而且在qualysconnect.util
中,他们甚至不执行getLogger
调用或getChild
调用,所以您无法在不影响整个模块的日志记录行为的情况下执行某些操作,而不会弄脏。
我能想到的唯一干净的选择是将他们处理日志的方式报告为错误,并提交一个补丁请求,其中您可以使用以下内容修改qualysconnect.util
日志记录语句:
import logging
logger = logging.getLogger('qualysconnect').getChild('util')
替换掉所有的logging.info()
,logging.debug()
...进入logger.info()
,logger.debug()
...
脏的选项:你可以对qualysconnect.util
模块打补丁,这样你就可以用一个记录器对象替换它的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
模块的所有注销,但我认为这不是您想要的。
https://stackoverflow.com/questions/17238654
复制相似问题