Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom parameter into Python logging 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

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.

like image 422
orion_tvv Avatar asked Oct 11 '13 12:10

orion_tvv


People also ask

What is getLogger in Python?

To start logging using the Python logging module, the factory function logging. getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not.

How do I create a multiple logging level in Python?

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO.


1 Answers

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()})
like image 190
julivico Avatar answered Oct 06 '22 08:10

julivico