使用 JSON 日志,我可以将多个值合并到一个键下吗
With JSON logs can I merge multiple values under a single key
我想在将其记录到控制台时将多个值合并到单个 JSON 键下。
这是一段代码
import logging
from pythonjsonlogger import jsonlogger
LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(threadName) %(message)'
logformatter = jsonlogger.JsonFormatter(LOG_FORMAT)
stdloghandler.setFormatter(logformatter)
logger.addHandler(stdloghandler)
生成的输出:
{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "filename": "xyz.py", "funcName": "abc", "threadName": "MainThread", "message": "..............."}
预期输出:
我想一键合并filename,funcName,threadName
像这样
{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "file": "xyz.py:abc:MainThread", "message": "..............."}
"file": "xyz.py:abc:MainThread"
我没有找到任何执行此操作的示例,也没有找到任何文档。
参考:https://pypi.org/project/python-json-logger/
您链接的文档 here shows how to create a custom format. You can also see the attributes 的 LogRecord
传递给函数调用。
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(self, log_record, record, message_dict):
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
custom_msg = f"{record.filename}:{record.funcName}:{record.threadName}"
log_record["file"] = custom_msg
formatter = CustomJsonFormatter('%(asctime)s %(levelname)s %(file)s %(message)')
我想在将其记录到控制台时将多个值合并到单个 JSON 键下。
这是一段代码
import logging
from pythonjsonlogger import jsonlogger
LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(threadName) %(message)'
logformatter = jsonlogger.JsonFormatter(LOG_FORMAT)
stdloghandler.setFormatter(logformatter)
logger.addHandler(stdloghandler)
生成的输出:
{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "filename": "xyz.py", "funcName": "abc", "threadName": "MainThread", "message": "..............."}
预期输出:
我想一键合并filename,funcName,threadName
像这样
{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "file": "xyz.py:abc:MainThread", "message": "..............."}
"file": "xyz.py:abc:MainThread"
我没有找到任何执行此操作的示例,也没有找到任何文档。 参考:https://pypi.org/project/python-json-logger/
您链接的文档 here shows how to create a custom format. You can also see the attributes 的 LogRecord
传递给函数调用。
class CustomJsonFormatter(jsonlogger.JsonFormatter):
def add_fields(self, log_record, record, message_dict):
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
custom_msg = f"{record.filename}:{record.funcName}:{record.threadName}"
log_record["file"] = custom_msg
formatter = CustomJsonFormatter('%(asctime)s %(levelname)s %(file)s %(message)')