python - 扩展问题“Python logging multiple files using the same logger”
问题描述
这是此查询的扩展。
我在配置文件中发现的错误是通过使用记录器,在任何时间点ws_in_.log
和ws_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.
解决方案
解决此问题的一种方法是将 logging.handlers.TimedRotatingFileHandler 替换为仅在收到要记录到文件的消息时打开或创建文件的版本。
另一种是只接受空文件的创建。
logging.handlers.TimedRotatingFileHandler 的实现如果在创建其实例时不存在日志文件,则会创建该日志文件。
推荐阅读
- login - 部署阶段因 cf 登录失败:使用不正确
- python - 我可以让 pytesseract 命令在引发错误的 pycharm 中正常工作吗
- syntax-error - wamp - 类似 615 的语法错误:无法识别的参数类型“类型”
- c# - Selenium Xpath - 需要匹配元素的孙子
- linux - 如何使用并行 linux 命令运行并行备份脚本
- python - 如果文件已存在,则附加到 CSV 文件
- nginx - Nginx 反向代理适用于 HTTPS,但不适用于 HTTP
- c++ - 自定义 key_comp 带有一个接受 c++ 集参数的类
- python - 如何在 Python 中以编程方式调用函数并以编程方式指定模块?
- powershell - 单独压缩多个文件夹 - 文件夹结构