11. 3. 2016 v IT

Django error reporting command

In situations when Django management commands are run on background for example using CRON, it would be good to be notified when such command crashes in the same way as we receive error report by e-mail when HTTP request crashes.

Unfortunately, Django doesn't support this feature by default. Here's my solution.

First, we create a management command, that will be parent for every other commands we create:

import sys
import logging

from django.core.management.base import BaseCommand

logger = logging.getLogger('commands')

class ErrorReportingCommand(BaseCommand):

    def execute(self, *args, **options):
        logger.info('Running command %s' % " ".join(sys.argv))
            super(ErrorReportingCommand, self).execute(*args, **options)
        except Exception as e:
            logger.error('Management Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            raise e

Then we setup logging to receive email every time command crashes:

   'loggers': {
        'commands': {
            'handlers': ['mail_admins', ],
            'level': 'INFO',
            'propagate': True,

The advantage of this solution is that method that we implement for our final commands are same as django documentation says, only the parent class is different:

from main.management.commands import ErrorReportingCommand

class Command(ErrorReportingCommand):
    help = 'Test errror reports work'

    def handle(self, *args, **kwargs):
        raise Exception('Error')

Čtěte dále