Django:登录manage.py会导致误导性异常和回溯

时间:2017-05-19 09:20:26

标签: python django logging

manage.py文件中,每次管理命令失败时,我都想向管理员发送电子邮件。

以下代码

manage.py

import logging
logger = logging.getLogger('management_commands')

try:
    execute_from_command_line(sys.argv)
except Exception as e:
    logger.error('Admin Command Error: %s', ' '.join(sys.argv),
                 exc_info=sys.exc_info())
    raise e

正在筹集

"The translation infrastructure cannot be initialized before the "

django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.`

实际错误实际上是ImportError: No module named django_inlinecss

记录器的我的设置是

LOGGING = {
    ...
    'handlers': {
        ...
        'mail_admins': {
            'class': 'django.utils.log.AdminEmailHandler',
            'level': 'ERROR',
            'include_html': True
        }
    },
    'loggers': {
        ...
        'management_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True
        }
    }
}

回溯的第一部分是

File "/usr/lib/python2.7/logging/__init__.py", line 1279, in _log
    self.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1289, in handle
    self.callHandlers(record)
File "/usr/lib/python2.7/logging/__init__.py", line 1329, in callHandlers
    hdlr.handle(record)
File "/usr/lib/python2.7/logging/__init__.py", line 757, in handle
    self.emit(record)
File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 128, in emit
    html_message = reporter.get_traceback_html() if self.include_html else None
File "/usr/local/lib/python2.7/dist-packages/django/views/debug.py", line 384, in get_traceback_html
    return t.render(c)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 210, in render
    return self._render(context)

这就是我最终认为可能存在与日志相关的问题。

为什么python日志库会让Django引发"The translation infrastructure cannot be initialized before the "

2 个答案:

答案 0 :(得分:2)

您已将“mail_admins”记录器配置为包含html,这会触发在调试视图中执行某些模板渲染,这本身需要初始化django的翻译系统。

这里最简单的解决方案是配置另一个没有“include_html”标志的处理程序,而是使用这一个代替你的记录器,即(警告:完全未经测试):

# logging config

LOGGING = {
    ...
    'handlers': {
        ...
        'mail_admins': {
            'class': 'django.utils.log.AdminEmailHandler',
            'level': 'ERROR',
            'include_html': True
        },
        'command_mail_admins': {
            'class': 'django.utils.log.AdminEmailHandler',
            'level': 'ERROR',
            'include_html': False
        },
    },
    'loggers': {
        ...
        'management_commands': {
            'handlers': ['command_mail_admins'],
            'level': 'ERROR',
            'propagate': True
        }
    }
}

答案 1 :(得分:0)

如果您尚未安装manage.py中列出的应用程序,则此版本的INSTALLED_APPS也可能发生此错误。

您可以删除manage.py中的except子句,以使异常显示时没有花哨的呈现,从而避免了令人困惑的错误。