python - 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'}, {...}, {...}]
这是可行的吗?我知道我可以在我的进程完成后发布处理这个日志文件,但我正在寻找一个更优雅的解决方案,因为我正在记录的某些内容本身就是相当大的对象。
解决方案
所以基于@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 进行斗争,以完成我打算完成的任务。
仍然希望有一个更优雅的解决方案。
推荐阅读
- javascript - 如何使用反应路由器 dom v5.0.1 获取参数
- jenkins - 我应该如何在 git scm 中使用相同的参数?
- wampserver - 我需要在 wamp 服务器上为 magento 2 安装 php 版本 7.2.17
- go-cd - 如何使基于声纳质量门的 GoCD 构建失败?
- docker - 使用 Kubernetes 启动 ProFtpd:发布安装卷
- angular - 保存与本地银行支付网关集成的 Angular 表单中的数据
- swift - ClosedRange 第二个参数变小并返回 nil
- gradle - Gradle checkstyleTest 失败“CheckstyleException:属性‘allowMissingPropertyJavadoc’不存在”
- angular - 如何在 Ionic/Angular 中预加载指令 + 相应的 HTML?(Mapbox 指令)
- mysql - 在查询生成器中查询不同的行