base.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. from django.core.management.base import BaseCommand
  4. from logging import getLogger
  5. logger = getLogger('django.commands')
  6. class LoggingBaseCommand(BaseCommand):
  7. """
  8. A subclass of BaseCommand that logs run time errors to `django.commands`.
  9. To use this, create a management command subclassing LoggingBaseCommand:
  10. from django_extensions.management.base import LoggingBaseCommand
  11. class Command(LoggingBaseCommand):
  12. help = 'Test error'
  13. def handle(self, *args, **options):
  14. raise Exception
  15. And then define a logging handler in settings.py:
  16. LOGGING = {
  17. ... # Other stuff here
  18. 'handlers': {
  19. 'mail_admins': {
  20. 'level': 'ERROR',
  21. 'filters': ['require_debug_false'],
  22. 'class': 'django.utils.log.AdminEmailHandler'
  23. },
  24. },
  25. 'loggers': {
  26. 'django.commands': {
  27. 'handlers': ['mail_admins'],
  28. 'level': 'ERROR',
  29. 'propagate': False,
  30. },
  31. }
  32. }
  33. """
  34. def execute(self, *args, **options):
  35. try:
  36. super().execute(*args, **options)
  37. except Exception as e:
  38. logger.error(e, exc_info=sys.exc_info(), extra={'status_code': 500})
  39. raise