Python 日志记录 - 两个记录器,两个日志文件 - 如何配置 logging.ini

Python logging - two loggers, two log files - how to configure logging.ini

拥有两个或更多不同的日志文件可能很实用。例如,对于 Rest 服务,有一个日志文件用于一般故障,另一个用于内容错误。

我尝试使用 INI 文件执行此操作,但出于某种原因,所有日志都会转到这两个文件。所以...

如果我希望来自 logger1 的所有日志都转到 logger1.loglogging.ini 会是什么样子以及来自 logger2 的所有日志转到 logger2.log:

logging.config.fileConfig('logging.ini')
logger1 = logging.getLogger('name1')
logger2 = logging.getLogger('name2')

这个有效:

python_logging.py

import logging
from logging import config

logging.config.fileConfig('logging.ini')
logger1 = logging.getLogger('name1')
logger2 = logging.getLogger('name2')

logger1.debug('This is logger1')
logger2.info('This is logger2')
logger1.warning('This is logger1')
logger1.error('This is logger1')
logger2.warning('This is logger2')
logger2.error('This is logger2')

logging.ini:

[loggers]
keys=root,name1,name2

[handlers]
keys=console_handler,file_handler_name1,file_handler_name2

[formatters]
keys=console_formatter,file_formatter

[logger_root]
level=INFO
handlers=

[logger_name1]
level=INFO
handlers=console_handler,file_handler_name1
qualname=name1

[logger_name2]
level=INFO
handlers=console_handler,file_handler_name2
qualname=name2

[handler_console_handler]
class=StreamHandler
formatter=console_formatter
args=(sys.stdout,)

[handler_file_handler_name1]
class=handlers.RotatingFileHandler
formatter=file_formatter
args=('name1.log','a',1000000,100)

[handler_file_handler_name2]
class=handlers.RotatingFileHandler
formatter=file_formatter
args=('name2.log','a',1000000,100)

[formatter_console_formatter]
format=%(asctime)s %(levelname)s | %(name)s | %(message)s'
datefmt='%d-%m-%Y %H:%M:%S

[formatter_file_formatter]
format=%(asctime)s %(levelname)s | %(name)s | %(message)s'
datefmt='%d-%m-%Y %H:%M:%S