简体   繁体   English

Django记录隐藏错误

[英]Django logging hiding errors

How do you make logging.error(msg) show the error message in a Django app? 如何使logging.error(msg)在Django应用中显示错误消息?

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. 通常建议使用Python的日志记录模块来处理Django中的日志记录输出,但是我发现它非常麻烦和复杂,并且很容易完全禁用所有输出。

In my Django settings, I have these logging settings: 在我的Django设置中,我具有以下日志记录设置:

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. 但是即使在启用DEBUG的本地开发服务器中,我也从未在控制台中看到这些错误。 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. 您可能看不到日志记录输出,因为您没有为脚本中的__name__安装记录器。

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' . 告诉日志记录框架安装名称为'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. 因此,只有记录到'django.request'消息才会产生任何输出,即,如果在您的示例代码中__name__不是'django.request' ,那么您将不会获得任何输出。

What you probably want is a root logger : 您可能想要的是root记录器

'': {
    '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. 可以为其他(django和非django)模块安装其他记录器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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