<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Command on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/command/</link>
    <description>Recent content in Command on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Sun, 08 Dec 2013 13:15:42 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/command/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>How to make django management commands send errors email to admins</title>
      <link>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</link>
      <pubDate>Sun, 08 Dec 2013 13:15:42 +0000</pubDate>
      <guid>https://mpcabd.xyz/make-django-management-commands-send-errors-email-admins/</guid>
      <description>&lt;p&gt;I usually use django’s &lt;a title=&#34;Writing custom django-admin commands&#34; href=&#34;https://docs.djangoproject.com/en/dev/howto/custom-management-commands/&#34; target=&#34;_blank&#34;&gt;custom management commands&lt;/a&gt; to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I usually use django’s <a title="Writing custom django-admin commands" href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/" target="_blank">custom management commands</a> to do different tasks on the web application, most of the times with a cron job running those commands. The problem is that when you’re using a cron job, you won’t get the beautiful django error email when something goes wrong.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg" rel="lightbox[403]" title="How to make django management commands send errors email to admins"><img class="aligncenter size-medium wp-image-404" alt="Django's error email sample" src="http://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg" width="300" height="207" srcset="https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email-300x207.jpg 300w, https://mpcabd.xyz/wp-content/uploads/2013/12/django-error-email.jpg 996w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>You can of course log all the commands you run and the cron jobs you have in files, but the problem is that sometimes you need to be notified instantly via your email, so here’s how to make django management commands send you the errors email.</p>
<h2 id="understanding-how-django8217s-error-email-works">Understanding how django’s error email works</h2>
<p>If you check django’s logging documentation you will find that it has a built-in handler called <a href="https://docs.djangoproject.com/en/dev/topics/logging/#django.utils.log.AdminEmailHandler" title="Django Logging AdminEmailHandler" target="_blank">AdminEmailHandler</a> this handler sends an email to the site admins for each log message it receives.</p>
<p>So basically all you need to do is to tell your django commands to log the errors using a logger with that handler, and you’ll receive the emails.</p>
<p>To do so define a logger in your <code>settings.py</code>:</p>
<pre class="lang:python decode:true">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_commands': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
</pre>
<p>And after that in your custom commands log the errors you face using the logger you defined:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
from django.core.management.base import BaseCommand
import sys

logger = getLogger('management_commands')

class Command(BaseCommand):
    def handle(self, *args, **options):
        try:
            #DO YOUR STUFF HERE
        except Exception as e:
            logger.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
            #Raise the exception again so it gets logged in standard error also.
            raise e
</pre>
<h2 id="enabling-the-logger-to-all-commands-in-one-configuration">Enabling the logger to all commands in one configuration</h2>
<p>You can also make all the commands (custom or not) send the error by email by editing <code>manage.py</code> almost the same way as we edited the command file above:</p>
<pre class="lang:python decode:true">from django.utils.log import getLogger
import sys

logger = getLogger('management_commands')

#Wrap this line with a try-catch execute_from_command_line(sys.argv)
    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
</pre>
<p>This way all the commands will send the error by email also to django admins.</p>
<p>Enjoy it!</p>]]></content:encoded>
    </item>
  </channel>
</rss>
