简体   繁体   中英

Django logging hiding errors

How do you make logging.error(msg) show the error message in a Django app?

It's often recommended to use Python's logging module to handle logging output in Django, but I'm finding it to be very cumbersome and complicated, and very easy to completely disable all output.

In my Django settings, I have these logging settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

And in a management command, I call the logger like:

import logging
LOG = logging.getLogger(__name__)
LOG.error('some error happened!')

but I never see these errors in a console, even from my local dev server with DEBUG enabled. What am I doing wrong?

You are probably not seeing the logging output, because you do not have a logger installed for whatever __name__ is in your script.

To explain:

'loggers': {
    'django.request': {
        'handlers': ['mail_admins'],
        'level': 'ERROR',
        'propagate': True,
    },
}

tells the logging framework to install a single logger with name 'django.request' . Hence only messages logged to 'django.request' will result in any output, ie if --in your example code-- __name__ is not 'django.request' , you will not get any output.

What you probably want is a root logger :

'': {
    'handlers': ['mail_admins'],
    'level': 'ERROR',
    'propagate': True, # this tells logger to send logging message
                        # to its parent (will send if set to True)
}

Additional loggers can be installed for different (django and non-django) modules.

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