如何在Python中禁用标准错误流的日志记录?这行不通:
import logging
logger = logging.getLogger()
logger.removeHandler(sys.stderr)
logger.warning('foobar') # emits 'foobar' on sys.stderr
如何在Python中禁用标准错误流的日志记录?这行不通:
import logging
logger = logging.getLogger()
logger.removeHandler(sys.stderr)
logger.warning('foobar') # emits 'foobar' on sys.stderr
当前回答
日志有以下结构:
loggers are arranged according to a namespace hierarchy with dot separators; each logger has a level (logging.WARNING by default for the root logger and logging.NOTSET by default for non-root loggers) and an effective level (the effective level of the parent logger for non-root loggers with a level logging.NOTSET and the level of the logger otherwise); each logger has a list of filters; each logger has a list of handlers; each handler has a level (logging.NOTSET by default); each handler has a list of filters.
日志记录有以下过程(由流程图表示):
因此,要禁用特定的记录器,您可以采用以下策略之一:
Set the level of the logger to logging.CRITICAL + 1. Using the main API: import logging logger = logging.getLogger("foo") logger.setLevel(logging.CRITICAL + 1) Using the config API: import logging.config logging.config.dictConfig({ "version": 1, "loggers": { "foo": { "level": logging.CRITICAL + 1 } } }) Add a filter lambda record: False to the logger. Using the main API: import logging logger = logging.getLogger("foo") logger.addFilter(lambda record: False) Using the config API: import logging.config logging.config.dictConfig({ "version": 1, "filters": { "all": { "()": lambda: (lambda record: False) } }, "loggers": { "foo": { "filters": ["all"] } } }) Remove the existing handlers of the logger, add a handler logging.NullHandler() to the logger (to prevent events from being handled by the handler logging.lastResort which is a logging.StreamHandler using the current stream sys.stderr and a level logging.WARNING) and set the attribute propagate of the logger to False (to prevent events from being handled by the handlers of the ancestor loggers of the logger). Using the main API: import logging logger = logging.getLogger("foo") for handler in logger.handlers.copy(): try: logger.removeHandler(handler) except ValueError: # in case another thread has already removed it pass logger.addHandler(logging.NullHandler()) logger.propagate = False Using the config API: import logging.config logging.config.dictConfig({ "version": 1, "handlers": { "null": { "class": "logging.NullHandler" } }, "loggers": { "foo": { "handlers": ["null"], "propagate": False } } })
警告。策略1和2只阻止记录器记录的事件被记录器的处理程序及其祖先记录器发出,策略3还阻止记录器的后代记录器记录的事件(例如logging.getLogger("foo.bar"))被记录器的处理程序及其祖先记录器发出。
请注意。—将日志记录器禁用的属性设置为True不是另一种策略,因为它不是公共API的一部分(参见https://bugs.python.org/issue36318):
import logging
logger = logging.getLogger("foo")
logger.disabled = True # DO NOT DO THIS
其他回答
我使用:
logger = logging.getLogger()
logger.disabled = True
... whatever you want ...
logger.disabled = False
这里有一些非常好的答案,但显然没有考虑太多最简单的答案(只从无穷开始)。
root_logger = logging.getLogger()
root_logger.disabled = True
这将禁用根日志记录器,从而禁用所有其他日志记录器。 我还没有真正测试过,但它应该是最快的。
从python 2.7的日志代码中,我看到了这一点
def handle(self, record):
"""
Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied.
"""
if (not self.disabled) and self.filter(record):
self.callHandlers(record)
这意味着当它被禁用时,不会调用任何处理程序,并且它应该比过滤到一个非常高的值或设置一个no-op处理程序更有效。
考虑到您已经创建了自己的处理程序,那么在将它们添加到日志记录器之前,您可以这样做:
logger.removeHandler(logger.handlers[0])
这将删除默认的StreamHandler。 当我在Python 3.8上遇到不需要的日志发送到stderr时,这对我来说是有效的,而这些日志本应该只记录到一个文件中。
这将防止所有来自第三个库的日志记录,就像这里描述的那样 https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library
logging.getLogger('somelogger').addHandler(logging.NullHandler())
子类化你想要暂时禁用的处理程序:
class ToggledHandler(logging.StreamHandler):
"""A handler one can turn on and off"""
def __init__(self, args, kwargs):
super(ToggledHandler, self).__init__(*args, **kwargs)
self.enabled = True # enabled by default
def enable(self):
"""enables"""
self.enabled = True
def disable(self):
"""disables"""
self.enabled = False
def emit(self, record):
"""emits, if enabled"""
if self.enabled:
# this is taken from the super's emit, implement your own
try:
msg = self.format(record)
stream = self.stream
stream.write(msg)
stream.write(self.terminator)
self.flush()
except Exception:
self.handleError(record)
通过名称查找处理程序非常简单:
_handler = [x for x in logging.getLogger('').handlers if x.name == your_handler_name]
if len(_handler) == 1:
_handler = _handler[0]
else:
raise Exception('Expected one handler but found {}'.format(len(_handler))
一旦发现:
_handler.disable()
doStuff()
_handler.enable()