如何在Python日志格式化程序中添加自定义参数? [英] How to add custom parameter into Python logging formatter?

查看:522
本文介绍了如何在Python日志格式化程序中添加自定义参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Flask框架的标准Python日志记录模块.我想将带有自定义参数-%(username)s的用户操作的所有记录的日志记录到文件中.Formatter:

I'm using standard Python logging module with Flask framework. I want to write logs to file with the all records of users actions with custom parameter - %(username)s to logging.Formatter:

admin - 2013-10-11 15:11:47,033 action0
user1 - 2013-10-11 15:11:48,033 action1
user2 - 2013-10-11 15:11:49,033 action2
admin - 2013-10-11 15:11:50,033 action3

我正在使用RotatingFileHandler:

I'm using RotatingFileHandler:

def get_user_name():
    return session.get("username", "")

file_handler = RotatingFileHandler(fname, maxBytes=1 * 1024 * 1024, backupCount=5)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
    '%(username)s - %(asctime)s %(levelname)-10s %(message)s  [in %(pathname)s:%(lineno)d]'
)) # how to insert get_user_name() instead %(username)s?

app.logger.addHandler(file_handler)

做这样的记录器的正确方法是什么?谢谢.

What is the right way to do such logger? Thanks.

推荐答案

u可以使用logging.LoggerAdapter

u can do it with logging.LoggerAdapter

myLogger = logging.LoggerAdapter(logging.getLogger("my-logger"), {"username" : get_user_name()})

这是您程序的完整解决方案.我使用字典来构建我的配置.最好,如果您有更多的记录器

Here is the complete solution for your program. I use a dict to build my configuration. It is better, if you have more logger

    def get_user_name():
        return session.get("username", "")

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'my_format': {
                'format': '%(username)s - %(asctime)s %(levelname)-10s %(message)s  [in %(pathname)s:%(lineno)d]'
            },
        },
        'handlers': {
            'my_handler': {
                'level': 'DEBUG',
                'class': 'logging.handlersRotatingFileHandler',
                'filename': fname,
                'maxBytes': 1 * 1024 * 1024,
                'backupCount': 5,
            },
        },
        'loggers': {
            'my_logger': {
                'handlers': ['my_handler'],
                'propagate': True,
                'level': 'DEBUG',
            },
        } }

logging.config.dictConfig(LOGGING) 
logging.LoggerAdapter(logging.getLogger('my_logger'),
                                           {"username" : get_user_name()})

这篇关于如何在Python日志格式化程序中添加自定义参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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