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

时间:2019-08-30 17:08:25

标签: python python-3.x python-logging

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

我尝试使用INI文件执行此操作,但是由于某些原因,所有日志都会同时进入两个文件。所以...

如果我希望所有logger1的日志都进入 logger1.log ,并且所有logger2的日志都进入 logger2, logging.ini 会是什么样子? .log

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

1 个答案:

答案 0 :(得分:0)

这有效:

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