52

我在 wsgi (web2py) 应用程序的每个请求上运行以下代码:

import logging, logging.handlers
from logging import StreamHandler, Formatter

def get_configured_logger(name):

    logger = logging.getLogger(name)

    if (len(logger.handlers) == 0):
        # This logger has no handlers, so we can assume it hasn't yet been configured (Django uses similiar trick)

        # === Configure logger ===

        # Create Formatted StreamHandler:
        FORMAT = "%(process)s %(thread)s: %(message)s"
        formatter = logging.Formatter(fmt=FORMAT)
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)
        logger.debug('CONFIGURING LOGGER')

    return logger

# Get app specific logger:
logger = get_configured_logger(request.application)
logger.debug("TEST")

这意味着使用我想要的格式化处理程序配置一次记录器。它有效,除了我的标准输出中有双重条目:

81893 4329050112: CONFIGURING LOGGER
DEBUG:dummy:CONFIGURING LOGGER
81893 4329050112: TEST
DEBUG:dummy:TEST

如何使用我的新格式化处理程序并摆脱/隐藏默认处理程序?

4

2 回答 2

75

也许下面的例子会有所帮助。基本上,您可以删除要禁用的记录器的处理程序,或者不要与您正在记录的记录器一起传播。

$ cat testlog.py
import logging
logging.basicConfig(filename='foo', level=logging.DEBUG)
root_logger = logging.getLogger()
root_logger.debug('bar')

my_logger = logging.getLogger('my_logger')
FORMAT = "%(process)s %(thread)s: %(message)s"
formatter = logging.Formatter(fmt=FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)

my_logger.addHandler(handler)
my_logger.setLevel(logging.DEBUG)
my_logger.info('baz')

my_logger.propagate = False
my_logger.info('foobar')

my_logger.propagate = True
my_logger.info('foobaz')
root_logger.handlers = []
my_logger.info('barbaz')

$ python testlog.py
5927 140735224465760: baz
5927 140735224465760: foobar
5927 140735224465760: foobaz
5927 140735224465760: barbaz

$ cat foo
DEBUG:root:bar
INFO:my_logger:baz
INFO:my_logger:foobaz
于 2012-08-06T01:12:25.027 回答
7

您可以使用以下方法从 getLogger() 中删除默认处理程序:

logging.getLogger().removeHandler(logging.getLogger().handlers[0])

或者在添加所需的处理程序之前先清除现有的处理程序:

logging.getLogger().handlers.clear()

这样做之后,这些日志将不再显示,除了您添加的新处理程序:

DEBUG: Do stuff
WARNING: Do stuff
于 2021-01-21T12:24:43.947 回答