首页 > 解决方案 > Python 作为字典或 JSON 登录文件

问题描述

我正在尝试设置日志记录,我可以在其中登录标准输出和文件。这是我使用以下代码完成的:

logging.basicConfig(
        level=logging.DEBUG, format='%(asctime)-15s %(levelname)-8s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S', handlers=[logging.FileHandler(path), logging.StreamHandler()])

这个输出是这样的:

2018-05-02 18:43:33,295 DEBUG    Starting new HTTPS connection (1): google.com
2018-05-02 18:43:33,385 DEBUG    https://google.com:443 "GET / HTTP/1.1" 301 220
2018-05-02 18:43:33,389 DEBUG    Starting new HTTPS connection (1): www.google.com
2018-05-02 18:43:33,490 DEBUG    https://www.google.com:443 "GET / HTTP/1.1" 200 None

我想要完成的是将此输出记录到文件中,而不是像打印到标准输出一样,而是作为类似于这样的字典或 JSON 对象(同时保持标准输出目前的状态):

[{'time': '2018-05-02 18:43:33,295', 'level': 'DEBUG', 'message': 'Starting new HTTPS connection (1): google.com'}, {...}, {...}]

这是可行的吗?我知道我可以在我的进程完成后发布处理这个日志文件,但我正在寻找一个更优雅的解决方案,因为我正在记录的某些内容本身就是相当大的对象。

标签: pythonlogging

解决方案


所以基于@abarnert,我发现了这个链接,它提供了一个很好的途径来让这个概念在很大程度上发挥作用。目前的代码是:

logger=logging.getLogger()
logger.setLevel(logging.DEBUG)

file_handler=logging.FileHandler('foo.log')
stream_handler=logging.StreamHandler()

stream_formatter=logging.Formatter(
    '%(asctime)-15s %(levelname)-8s %(message)s')
file_formatter=logging.Formatter(
    "{'time':'%(asctime)s', 'name': '%(name)s', \
    'level': '%(levelname)s', 'message': '%(message)s'}"
)

file_handler.setFormatter(file_formatter)
stream_handler.setFormatter(stream_formatter)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

虽然它不完全满足要求,但它不需要任何预处理,并允许我创建两个日志处理程序。

之后,我可以使用类似的东西:

with open('foo.log') as f:
    logs = f.read().splitlines()
for l in logs:
    for key, value in eval(l):
        do something ...

拉取dict对象,而不是与格式不正确的 JSON 进行斗争,以完成我打算完成的任务。

仍然希望有一个更优雅的解决方案。


推荐阅读