【发布时间】:2021-07-07 03:39:26
【问题描述】:
最近发现了JSON-log-formatter,想用它来用JSON写我的日志输出。在脚本中配置它相对简单,但我现有的大部分代码都利用 logging.config.dictConfig 从 YAML 文件加载日志配置,因此我可以轻松配置日志记录而无需修改脚本本身,我想不通如何在配置中添加一个 python 模块作为格式化程序。
当前 YAML
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s | %(name)s | %(funcName)s() | %(levelname)s | %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
file_handler:
class: logging.handlers.TimedRotatingFileHandler
level: INFO
formatter: simple
filename: LogFile.log
encoding: utf8
backupCount: 30
encoding: utf8
when: 'midnight'
interval: 1
delay: True
loggers:
my_module:
level: ERROR
handlers: [console]
propagate: no
root:
level: INFO
handlers: [console, file_handler]
上述配置有效,但我不知道如何使用该模块将格式化程序更改为 JSON。像这样的东西(我知道这不起作用):
formatters:
simple:
format: json_log_formatter.VerboseJSONFormatter()
Python 加载 YAML
import logging.config
import json_log_formatter
import yaml
with open('./logging.yaml', 'r') as stream:
logConfig = yaml.load(stream, Loader=yaml.FullLoader)
logging.config.dictConfig(logConfig)
我知道 python 只是将 YAML 加载到字典对象中,然后基于该字典配置日志记录,但是我如何设置格式化程序以便它正确引用 JSON 日志记录模块并使用它?
【问题讨论】:
标签: python python-3.x logging