简体   繁体   中英

How to pass extra arguments to the django log formatter

I am trying to do the following:

    # settings.py
    'json': {
        'format': 'Avails: {"levelname": "%(levelname)s", "asctime": "%(asctime)s", "funcName": "%(funcName)s", "filename": "%(filename)s", "lineno": "%(lineno)s", "message": "%(message)s"}',
    },

And in the view:

log.info('this is my message', extra={'user': request.user}

How would I grab the extra info in the log formatter?

The user in extra can be added in the logging json formatter as

'json': {
    'format': (
        'Avails: {'
            '"levelname": "%(levelname)s",'
            '"asctime": "%(asctime)s",'
            '"funcName": "%(funcName)s",'
            '"filename": "%(filename)s",'
            '"lineno": "%(lineno)s",'
            '"message": "%(message)s",' 
            '"user": "%(user)s"'
        '}',
    )
},

Note that you need to pass a string value for user instead of the user object in the extra options. When this is not a string object, the __repr__ or __str__ value of the object passed replaces the corresponding conversion specification in the format string.

log.info('this was your message :D', extra={'user': request.user.pk}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM