Created
March 28, 2017 21:08
-
-
Save JordanReiter/8bbf6177f5d286b80158f0d423daa1a2 to your computer and use it in GitHub Desktop.
Use the EmailAdminsOnErrorCommand class instead of BaseCommand so that your Django management commands send error emails to admins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This file provides a base Command class that handles sending errors via mail_admins | |
# Make sure to adjust the LOGGING variable in settings | |
# Credit to Abdulla Diab: https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/ | |
import sys | |
import logging | |
from django.core.management import BaseCommand | |
logger = logging.getLogger('management.command') | |
class EmailAdminsOnErrorCommand(BaseCommand): | |
def execute(self, *args, **options): | |
try: | |
return super(EmailAdminsOnErrorCommand, self).execute(*args, **options) | |
except Exception as e: | |
command_name = self.__class__.__module__.split('.')[-1] | |
if self._called_from_command_line: | |
logger.error('Management Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info()) | |
else: | |
logger.error('Management Command Error (Run as command): %s', command_name, exc_info=sys.exc_info()) | |
#Raise the exception again so it gets logged in standard error also. | |
raise e |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# adjust your LOGGING setting | |
# The key is adding management.command under loggers, | |
# and setting it to use the mail_admins handler | |
LOGGING = { | |
#OTHER OPTIONS | |
'filters': { | |
#OTHER FILTERS | |
'require_debug_false': { | |
'()': 'django.utils.log.RequireDebugFalse' | |
} | |
}, | |
'handlers': { | |
#OTHER HANDLERS | |
'mail_admins': { | |
'level': 'ERROR', | |
'filters': ['require_debug_false'], | |
'class': 'django.utils.log.AdminEmailHandler', | |
'include_html': True | |
} | |
}, | |
'loggers': { | |
#OTHER LOGGERS | |
'management.command': { | |
'handlers': ['mail_admins'], | |
'level': 'ERROR', | |
'propagate': True, | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment