Django logging custom attributes in formatter

后端 未结 3 840
挽巷
挽巷 2021-02-07 05:37

How can Django use logging to log using custom attributes in the formatter? I\'m thinking of logging the logged in username for example.

In the settings.py

3条回答
  •  甜味超标
    2021-02-07 05:41

    You can use a filter to add your custom attribute. For example :

    def add_my_custom_attribute(record):
        record.myAttribute = 'myValue'
        record.username = record.request.user.username 
        return True
    
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'filters': {
            ...
            'add_my_custom_attribute': {
                '()': 'django.utils.log.CallbackFilter',
                'callback': add_my_custom_attribute,
            }
        },
        'handlers': {
            ...
            'django.server': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'filters': ['add_my_custom_attribute'],
                'formatter': 'django.server',
            },            
        },
        ...
    }
    

    By installing a filter, you can process each log record and decide whether it should be passed from logger to handler.

    The filter get the log record which contains all the details of log (i.e : time, severity, request, status code).

    The attributes of the record are used by the formatter to format it to string message. If you add your custom attributes to that record - they will also be available to the formatter.

提交回复
热议问题