How to add custom parameter into Python logging formatter?

前端 未结 2 1601
梦如初夏
梦如初夏 2021-02-05 17:43

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 loggin

2条回答
  •  旧时难觅i
    2021-02-05 18:06

    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()})
    

提交回复
热议问题