首页 > 解决方案 > 扩展问题“Python logging multiple files using the same logger”

问题描述

这是此查询的扩展。

我在配置文件中发现的错误是通过使用记录器,在任何时间点ws_in_.logws_out_.log文件都会被创建,即使它们在不同的处理程序下并且用于不同的进程。我的意思是,如果我运行IN进程,那么相应IN的日志将被登录到ws_in.log文件中。但随之而来的是一个空ws_out.log文件。

那么有什么方法可以限制为各个进程创建日志文件。请帮助。

感谢和问候Pragyan

[loggers]
keys=root, ws_in_log, ws_out_log

[handlers]
keys=consoleHandler, ws_in_hand, ws_out_hand

[formatters]
keys=generic_form

[loggers]
keys=root, ws_in_log, ws_out_log

[handlers]
keys=consoleHandler, ws_in_hand, ws_out_hand

[formatters]
keys=generic_form

[logger_root]
handlers=consoleHandler
level=NOTSET

[logger_ws_in_log]
level=NOTSET
handlers=ws_in_hand
qualname=ws_in_log

[logger_ws_out_log]
level=NOTSET
handlers=ws_out_hand
qualname=ws_out_log

[handler_ws_in_hand]
class=logging.handlers.TimedRotatingFileHandler
level=NOTSET
formatter=generic_form
args=('/path/ws_in_.log', 'h', 1, 0, None, False, True)

[handler_ws_out_hand]
class=logging.handlers.TimedRotatingFileHandler
level=NOTSET
formatter=generic_form
args=('/path/em/ws_out_.log', 'h', 1, 0, None, False, True)

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

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

我正在通过脚本 IN.py 使用上述配置文件,

import logging.config

logging.config.fileConfig('x.ini')
logger=logging.getLogger('ws_in_log')
class Car(object):
    def __init__(self,brand,model,color):
        self.brand = brand
        self.model = model
        self.color = color

    def drive(self):
        self.condition = 'Used'
        print("in drive")
def drive(msg):
    logger.debug("in script function")
    logger.debug(msg)

Expected : only "ws_in_.log" file shoud be created if "IN" script get called.
Actual: Both "ws_in_.log" and "ws_out_.log" files are getting created if only "IN" script get called.

标签: pythonloggingconfig

解决方案


解决此问题的一种方法是将 logging.handlers.TimedRotatingFileHandler 替换为仅在收到要记录到文件的消息时打开或创建文件的版本。

另一种是只接受空文件的创建。

logging.handlers.TimedRotatingFileHandler 的实现如果在创建其实例时不存在日志文件,则会创建该日志文件。


推荐阅读