我使用了日志模块,发现了一些对我来说不太清楚的事情。使用json配置文件进行Python日志记录
首先,因为它是一个大程序,我希望代码尽可能简单,因此使用json配置文件。
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
},
"extra": {"format":"%(asctime)-16s %(name)-8s %(filename)-12s %(lineno)-6s %(funcName)-30s %(levelname)-8s %(message)s",
"datefmt":"%m-%d %H:%M:%S"}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"info_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "INFO",
"formatter": "simple",
"filename": "info.log",
"maxBytes": 10485760,
"backupCount": 40,
"encoding": "utf8"
},
"error_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "ERROR",
"formatter": "simple",
"filename": "errors.log",
"maxBytes": 10485760,
"backupCount": 40,
"encoding": "utf8"
}
},
"loggers": {
"my_module": {
"level": "ERROR",
"handlers": ["console"],
"propagate": "no"
}
},
"root": {
"level": "INFO",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
此JSON文件被导入并使用。它似乎工作正常。 不幸的是有一些问题。 完成代码(仍在工作)后,记录器不会关闭文件。由于这一点,他将在下一次运行中将新的运行追加到旧的日志文件中。没有可能删除它或truncate()没有问题。 因此我想删除处理程序写入文件。不幸的是,它看起来像logger.handlers是空的,因此我无法在任何地方找到它们。大概有一个想法?
此外,日志文件还有一个主要问题。记录器只是追加所有新东西而不开始新行。结果是无尽的单行日志。
主测试程序:
import sys
import os
import json
import logging.config
import my_module
def setup_logging(
default_path='logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
def main():
setup_logging()
logger = logging.getLogger(__name__)
logger.info('Startlogging:')
my_module.foo()
b = my_module.Bar()
b.bar()
print logger.handlers
if __name__ == '__main__':
main()
你可以显示实际日志记录的代码吗?你也看过这里吗? https://docs.python.org/3/library/logging.html – sietse85
'进口记录
高清富():
记录= logging.getLogger(__ name__)
logger.info('嗨,FOO - 信息 ')
logger.debug(' 嗨,富 - 调试 ')
logger.error(' 嗨,富 - 错误“)
Bar类(对象):
高清__init __(自我,记录器=无):
self.logger = logger或logging.getLogger(__ name__)
def bar(self):
('嗨,酒吧 - 信息')
self.logger.debug('嗨,酒吧 - 调试')
self.logger.error('嗨,酒吧 - 错误')
' – RandomMario
所以你现在已经得到了整个代码。认为最大的问题是最后不要关闭处理程序。 BUt作为logger.handlers返回[]我不知道如何手动关闭它们 – RandomMario