在Django命令中记录异常

时间:2016-09-22 09:42:35

标签: python django logging

我在Django中实现了自定义命令,它们的异常没有记录在我的日志文件中。

我创建了一个应用程序my_app_with_commands,其中包含一个目录management/commands,其中我实现了一些命令。

示例命令可能是这样的,由于异常而崩溃:

import logging
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = 'Do something usful'
    log = logging.getLogger(__name__)

    def handle(self, *args, **options):
        self.log.info('Starting...')
        raise RuntimeError('Something bad happened')
        self.log.info('Done.')

我的日志配置如下:

LOGGING = { 
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'normal': {
            'format': '%(asctime)s %(module)s %(levelname)s %(message)s',
        }
    },  
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, '..', 'logs', 'my_log.log'),
            'formatter': 'normal',
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        }
    },  
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
        'my_app_with_commands': {
            'handlers': ['file', 'mail_admins'],
            'level': 'INFO',
            'propagate': True,
        },
    },  
}

当我运行该命令时,对记录器的调用已成功保存到my_log.log文件:

2016-09-22 11:37:01,514 test INFO Starting...

但每个回溯的异常都会显示在调用命令的stderr中:

[mgarcia@localhost src]$ ./manage.py test
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/mgarcia/anaconda3/envs/my_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/home/mgarcia/anaconda3/envs/my_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/mgarcia/anaconda3/envs/my_env/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/mgarcia/anaconda3/envs/my_env/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/home/mgarcia/my_project/src/my_app_with_commands/management/commands/test_command.py", line 11, in handle
    raise RuntimeError('Something bad happened')
RuntimeError: Something bad happened

我可以在每个命令中实现try/except块,并手动记录异常。但是我可以使用Django设置捕获异常并将其保存到我的日志文件而不是stderr吗?

1 个答案:

答案 0 :(得分:0)

其中一种方法 - 您可以修改 manage.py 文件以在其中添加try / except块:

log = logging.getLogger('my_app_with_commands')
# ...
try:
    execute_from_command_line(sys.argv)
except Exception as e:
    log.error('your exception log')
    raise e