如何重命名"levelname"?达到“水平"在Python日志消息? [英] How can I rename "levelname" to "level" in Python log messages?

查看:298
本文介绍了如何重命名"levelname"?达到“水平"在Python日志消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的Python日志记录配置:

I have a Python logging configuration which looks like this:

LOGGING_CONFIG:
    version: 1
    formatters:
        human:
            class: logging.Formatter
            format: '[%(asctime)s]:[%(levelname)s]: %(message)s'
        json:
            class: pythonjsonlogger.jsonlogger.JsonFormatter
            format: '%(asctime)s %(levelname)s %(message)s'
    handlers:
        console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: json  # change this to 'human' when you run it locally, json in production
        file:
            class: logging.FileHandler
            filename: logfile.log
            level: DEBUG
            formatter: json
    root:  # Logging for 3rd party stuff
        level: INFO
        handlers:
            - console
            - file
    project_name:  # Logging this module
        level: DEBUG
        handlers:
            - console
            - file

对于另一个系统,我需要结构化日志记录具有一些固定名称.一个示例是它不应为levelname,而应为level.如何重命名日志字段?

For another system, I need the structured logging to have some fixed names. One example is that it should not be levelname, but level. How can I rename log fields?

我所拥有的:

{"asctime": "2018-10-22 14:50:19,923", "levelname": "info", "message": "foobar"}

我想要什么:

{"asctime": "2018-10-22 14:50:19,923", "level": "info", "message": "foobar"}

推荐答案

levelname不会出现在普通的Python记录器中,而是出现在您使用的自定义格式化程序中.据我了解,您可以使用以下片段来自定义其输出的字典:

levelname will not appear in normal Python loggers but in the custom formatter you used. From what I understood you could use below snippet to customize the dict it outputs:

class CustomJsonFormatter(jsonlogger.JsonFormatter):
    def add_fields(self, log_record, record, message_dict):
        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
        log_record['level'] = log_record['levelname']
        del log_record['levelname']

然后用地址CustomJsonFormatter替换pythonjsonlogger.jsonlogger.JsonFormatter.

这篇关于如何重命名"levelname"?达到“水平"在Python日志消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆