Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logging: Change "WARN" to "INFO"

If our Django web application returns a 404, we see this in the logs:

2017-11-21 12:48:26 django.request.get_response: WARNING Not Found: /foooooo

I would like to change this particular line created by get_response() from WARN to INFO.

How to configure this with Django and Python?

An alternative solution would be to ignore this line, but WARN to INFO would be preferred.

like image 251
guettli Avatar asked Nov 21 '17 12:11

guettli


2 Answers

You can't do this easily, because the Django developers have decided that this particular event is important enough to be classed as a WARNING.

However, you can convert it to INFO when writing to a log, by adding an instance of a logging.Filter subclass which changes the level in the LogRecord from WARNING to INFO, or filters out the message altogether.

The filter should be added to any handler whose output should be changed in this way. This can be done using standard Django logging configuration mechanisms.

like image 124
Vinay Sajip Avatar answered Sep 23 '22 04:09

Vinay Sajip


Firstly create logger filter

def change_404_level_to_INFO(record):
    if record.status_code == 404:
        record.levelname = 'INFO'
    return True

After that in LOGGING add this filter and set filter on logger

LOGGING = {
....
    'filters': {
        'change_404_to_INFO': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': change_404_to_INFO`,
        },
    },
....
    'loggers': {
        'django.request': {
            'handlers': ['console',],
            'level': 'DEBUG',
            'propagate: False,
            'filters': ['change_404_to_INFO'],
        },
    }
....
}
like image 20
chinskiy Avatar answered Sep 21 '22 04:09

chinskiy