如何只记录某个levelname python日志

2024-09-29 19:30:26 发布

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

[loggers]
keys=root

[handlers]
keys=consoleHandler,errorHandler,debugHandler

[formatters]
keys=errorFormatter,debugFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler,errorHandler,debugHandler
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=debugFormatter
args=(sys.stdout,)

[handler_errorHandler]
class=FileHandler
level=ERROR
formatter=errorFormatter
args=('errors.log',)

[handler_debugHandler]
class=FileHandler
level=DEBUG
formatter=debugFormatter
args=('debugs.log',)

[formatter_errorFormatter]
style={
format=
    {asctime} - {name} - {levelname} - line {lineno} - {message}
datefmt=%d/%m/%y - %H:%M:%S

[formatter_debugFormatter]
style={
format={asctime} - {name} - {levelname} - {message}
datefmt=%d/%m/%y - %H:%M:%S

如果我有一个像上面这样的配置文件,我如何访问debugHandler以便像debugHandler.addFilter(my_custom_filter)那样做?你知道吗

我基本上是想让DEBUG消息被发送到debugs.log并且ERROR消息被发送到errors.log,但是目前ERROR消息也被发送到debugs.log,这是我不想要的。现在,基于this StackOverflow post,这可以通过过滤器实现,但是为了添加过滤器,我需要一个logging.Handler对象,我不知道如何获得一个。你知道吗

提前感谢:~)


Tags: debuglogformatterargserrorkeyslevelclass
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:26

是的,在调试处理程序上需要一个过滤器,但是不能通过fileConfig添加过滤器。你知道吗

从文档中:

The fileConfig() API is older than the dictConfig() API and does not provide functionality to cover certain aspects of logging. For example, you cannot configure Filter objects, which provide for filtering of messages beyond simple integer levels, using fileConfig(). If you need to have instances of Filter in your logging configuration, you will need to use dictConfig(). Note that future enhancements to configuration functionality will be added to dictConfig(), so it’s worth considering transitioning to this newer API when it’s convenient to do so.

因此,考虑使用dictConfig(不管您的配置如何,都不应该有任何理由不切换到dictConfig,因为它更好、更新、更灵活,而且将来所有的好东西都会被添加进来)。你知道吗

因此,转换到dictConfig的配置看起来像这样(可以按原样粘贴和测试):

import logging
from logging import config

class FileFilter:
    """Allow only LogRecords whose severity levels are below ERROR."""

    def __call__(self, log):
        if log.levelno < logging.ERROR:
            return 1
        else:
            return 0


logging_config = {
    'version': 1,
    'formatters': {
        'error_formatter': {
            'format': '{asctime} - {name} - {levelname} - line {lineno} - {message}',
            'style': '{',
            'datefmt': '%d/%m/%y - %H:%M:%S',
        },
        'debug_formatter': {
            'format': '{asctime} - {name} - {levelname} - {message}',
            'style': '{',
            'datefmt': '%d/%m/%y - %H:%M:%S',
        },
    },
    'filters': {
        'file_filter': {
            '()': FileFilter,
        },
    },
    'handlers': {
        'console_handler': {
            'class': 'logging.StreamHandler',
            'formatter': 'debug_formatter',
        },
        'error_handler': {
            'class': 'logging.FileHandler',
            'formatter': 'debug_formatter',
            'level': 'ERROR',
            'filename': 'errors.log',
        },
        'debug_handler': {
            'class': 'logging.FileHandler',
            'formatter': 'debug_formatter',
            'filters': ['file_filter'],
            'filename': 'debug.log',
        },
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['console_handler', 'error_handler', 'debug_handler'],
    },
}

config.dictConfig(logging_config)

logger = logging.getLogger(__name__)

# these get logged to the console and only to the debugs.log file
# if you want just the debug messages logged to the file, adjust the filter
logger.debug('this is a debug message')
logger.info('this is an info message')
logger.warning('this is a warning message')

# this get logged to the console and only to the errors.log file
logger.error('this is an error message')
logger.critical('this is a critical message')

将输出:

27/09/19 - 07:52:44 - __main__ - DEBUG - this is a debug message  # also to debug.log
27/09/19 - 07:52:44 - __main__ - INFO - this is an info message  # also to debug.log
27/09/19 - 07:52:44 - __main__ - WARNING - this is a warning message  # also to debug.log
27/09/19 - 07:52:44 - __main__ - ERROR - this is an error message  # also to errors.log but not to debug.log
27/09/19 - 07:52:44 - __main__ - CRITICAL - this is a critical message  # also to errors.log but not to debug.log

如果您出于某种神秘的原因(我看不到任何原因)坚持使用旧的API,fileConfig,请参阅this answer,它使用自定义格式化程序,实现同样的功能,没有过滤器。你知道吗

相关问题 更多 >

    热门问题