简体   繁体   English

为根记录器配置格式

[英]Configure formatting for root logger

I use this code to configure the given logger, or the root logger:我使用此代码来配置给定的记录器或根记录器:

def configure_logging(level='INFO', logger=None):
    """Configures a simple console logger with the givel level"""
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    console = logging.StreamHandler()
    console.setFormatter(formatter)
    console.setLevel(level)
    logger = logger or logging.getLogger()  # either the given logger or the root logger
    logger.setLevel(level)
    logger.addHandler(console)

Log messages are then duplicated when configuring the root logger.然后在配置根记录器时复制日志消息。 It seems that both the newly configured console handler and the default handler are active for the root logger.似乎新配置的console处理程序和默认处理程序对于根记录器都是活动的。

How can I disable / remove the default handler of the root logger, and enable exclusively the console handler?如何禁用/删除根记录器的默认处理程序,并专门启用console处理程序?

Or alternatively, how can I setup formatting of the default handler for the root logger?或者,我如何为根记录器设置默认处理程序的格式?

This more or less solves my problem:这或多或少地解决了我的问题:

def configure_logging(level='INFO', logger=None):
    """
    Configures a simple console logger with the givel level.
    A usecase is to change the formatting of the default handler of the root logger
    """
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger = logger or logging.getLogger()  # either the given logger or the root logger
    logger.setLevel(level)
    # If the logger has handlers, we configure the first one. Otherwise we add a handler and configure it
    if logger.handlers:
        console = logger.handlers[0]  # we assume the first handler is the one we want to configure
    else:
        console = logging.StreamHandler()
        logger.addHandler(console)
    console.setFormatter(formatter)
    console.setLevel(level)

The logging module has a default setup 'built in'.日志模块具有“内置”的默认设置。 If you just want to change the format of the root logger you can use dictConfig and continue customizing from there.如果您只想更改根记录器的格式,您可以使用dictConfig并从那里继续自定义。

Here is a snippet from my logger configuration这是我的记录器配置中的一个片段

 cfg = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': _format
        },
    },
    'handlers': {},
    'loggers': {
        '': {
            'handlers': [],
            'level': level.upper(),
            'propagate': True

        }
    }
}

if console:
    cfg['handlers']['console'] = {
        'class': 'logging.StreamHandler',
        'level': level.upper(),
        'formatter': 'standard',
    }
    # noinspection PyUnresolvedReferences
    cfg['loggers']['']['handlers'].append('console')

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

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