Error reporting

When you’re running a public site you should always turn off theDEBUG setting. That will make your server run much faster, and willalso prevent malicious users from seeing details of your application that can berevealed by the error pages.

However, running with DEBUG set to False means you’ll never seeerrors generated by your site – everyone will instead see your public errorpages. You need to keep track of errors that occur in deployed sites, so Djangocan be configured to create reports with details about those errors.

Email reports

Server errors

When DEBUG is False, Django will email the users listed in theADMINS setting whenever your code raises an unhandled exception andresults in an internal server error (HTTP status code 500). This gives theadministrators immediate notification of any errors. The ADMINS willget a description of the error, a complete Python traceback, and details aboutthe HTTP request that caused the error.

Note

In order to send email, Django requires a few settings telling ithow to connect to your mail server. At the very least, you’ll needto specify EMAIL_HOST and possiblyEMAIL_HOST_USER and EMAIL_HOST_PASSWORD,though other settings may be also required depending on your mailserver’s configuration. Consult the Django settingsdocumentation for a full list of email-relatedsettings.

By default, Django will send email from root@localhost. However, some mailproviders reject all email from this address. To use a different senderaddress, modify the SERVER_EMAIL setting.

To activate this behavior, put the email addresses of the recipients in theADMINS setting.

See also

Server error emails are sent using the logging framework, so you cancustomize this behavior by customizing your logging configuration.

404 errors

Django can also be configured to email errors about broken links (404 “pagenot found” errors). Django sends emails about 404 errors when:

  • DEBUG is False;
  • Your MIDDLEWARE setting includesdjango.middleware.common.BrokenLinkEmailsMiddleware.If those conditions are met, Django will email the users listed in theMANAGERS setting whenever your code raises a 404 and the request hasa referer. It doesn’t bother to email for 404s that don’t have a referer –those are usually people typing in broken URLs or broken Web bots. It alsoignores 404s when the referer is equal to the requested URL, since thisbehavior is from broken Web bots too.

Note

BrokenLinkEmailsMiddleware must appearbefore other middleware that intercepts 404 errors, such asLocaleMiddleware orFlatpageFallbackMiddleware.Put it towards the top of your MIDDLEWARE setting.

You can tell Django to stop reporting particular 404s by tweaking theIGNORABLE_404_URLS setting. It should be a list of compiledregular expression objects. For example:

  1. import re
  2. IGNORABLE_404_URLS = [
  3. re.compile(r'\.(php|cgi)$'),
  4. re.compile(r'^/phpmyadmin/'),
  5. ]

In this example, a 404 to any URL ending with .php or .cgi will not bereported. Neither will any URL starting with /phpmyadmin/.

The following example shows how to exclude some conventional URLs that browsers andcrawlers often request:

  1. import re
  2. IGNORABLE_404_URLS = [
  3. re.compile(r'^/apple-touch-icon.*\.png$'),
  4. re.compile(r'^/favicon\.ico$'),
  5. re.compile(r'^/robots\.txt$'),
  6. ]

(Note that these are regular expressions, so we put a backslash in front ofperiods to escape them.)

If you’d like to customize the behavior ofdjango.middleware.common.BrokenLinkEmailsMiddleware further (forexample to ignore requests coming from web crawlers), you should subclass itand override its methods.

See also

404 errors are logged using the logging framework. By default, these logrecords are ignored, but you can use them for error reporting by writing ahandler and configuring logging appropriately.

Filtering error reports

Warning

Filtering sensitive data is a hard problem, and it’s nearly impossible toguarantee that sensitive data won’t leak into an error report. Therefore,error reports should only be available to trusted team members and youshould avoid transmitting error reports unencrypted over the Internet(such as through email).

Filtering sensitive information

Error reports are really helpful for debugging errors, so it is generallyuseful to record as much relevant information about those errors as possible.For example, by default Django records the full traceback for theexception raised, each traceback frame’s local variables, and theHttpRequest’s attributes.

However, sometimes certain types of information may be too sensitive and thusmay not be appropriate to be kept track of, for example a user’s password orcredit card number. So in addition to filtering out settings that appear to besensitive as described in the DEBUG documentation, Django offers aset of function decorators to help you control which information should befiltered out of error reports in a production environment (that is, whereDEBUG is set to False): sensitive_variables() andsensitive_post_parameters().

  • sensitivevariables(*variables_)
  • If a function (either a view or any regular callback) in your code useslocal variables susceptible to contain sensitive information, you mayprevent the values of those variables from being included in error reportsusing the sensitive_variables decorator:
  1. from django.views.decorators.debug import sensitive_variables
  2.  
  3. @sensitive_variables('user', 'pw', 'cc')
  4. def process_info(user):
  5. pw = user.pass_word
  6. cc = user.credit_card_number
  7. name = user.name
  8. ...

In the above example, the values for the user, pw and ccvariables will be hidden and replaced with stars (**) in theerror reports, whereas the value of the name variable will bedisclosed.

To systematically hide all local variables of a function from error logs,do not provide any argument to the sensitive_variables decorator:

  1. @sensitive_variables()def my_function():

When using multiple decorators

If the variable you want to hide is also a function argument (e.g.‘user’ in the following example), and if the decorated function hasmultiple decorators, then make sure to place @sensitive_variablesat the top of the decorator chain. This way it will also hide thefunction argument as it gets passed through the other decorators:

  1. @sensitive_variables('user', 'pw', 'cc')@some_decorator@another_decoratordef process_info(user):

  • sensitivepost_parameters(*parameters_)
  • If one of your views receives an HttpRequest objectwith POST parameters susceptible tocontain sensitive information, you may prevent the values of thoseparameters from being included in the error reports using thesensitive_post_parameters decorator:
  1. from django.views.decorators.debug import sensitive_post_parameters
  2.  
  3. @sensitive_post_parameters('pass_word', 'credit_card_number')
  4. def record_user_profile(request):
  5. UserProfile.create(
  6. user=request.user,
  7. password=request.POST['pass_word'],
  8. credit_card=request.POST['credit_card_number'],
  9. name=request.POST['name'],
  10. )
  11. ...

In the above example, the values for the password andcredit_card_number POST parameters will be hidden and replaced withstars (**_) in the request’s representation inside the errorreports, whereas the value of the name parameter will be disclosed.

To systematically hide all POST parameters of a request in error reports,do not provide any argument to the sensitive_post_parameters decorator:

  1. @sensitive_post_parameters()def my_view(request):

All POST parameters are systematically filtered out of error reports forcertain django.contrib.auth.views views (login,password_reset_confirm, password_change, and add_view anduser_change_password in the auth admin) to prevent the leaking ofsensitive information such as user passwords.

Custom error reports

All sensitive_variables() and sensitive_post_parameters() do is,respectively, annotate the decorated function with the names of sensitivevariables and annotate the HttpRequest object with the names of sensitivePOST parameters, so that this sensitive information can later be filtered outof reports when an error occurs. The actual filtering is done by Django’sdefault error reporter filter:django.views.debug.SafeExceptionReporterFilter. This filter uses thedecorators’ annotations to replace the corresponding values with stars(**) when the error reports are produced. If you wish to override orcustomize this default behavior for your entire site, you need to define yourown filter class and tell Django to use it via theDEFAULT_EXCEPTION_REPORTER_FILTER setting:

  1. DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'

You may also control in a more granular way which filter to use within anygiven view by setting the HttpRequest’s exception_reporter_filterattribute:

  1. def my_view(request):
  2. if request.user.is_authenticated:
  3. request.exception_reporter_filter = CustomExceptionReporterFilter()
  4. ...

Your custom filter class needs to inherit fromdjango.views.debug.SafeExceptionReporterFilter and may override thefollowing methods:

  • class SafeExceptionReporterFilter
  • SafeExceptionReporterFilter.isactive(_request)
  • Returns True to activate the filtering operated in the other methods.By default the filter is active if DEBUG is False.

  • SafeExceptionReporterFilter.getpost_parameters(_request)

  • Returns the filtered dictionary of POST parameters. By default it replacesthe values of sensitive parameters with stars (**).

  • SafeExceptionReporterFilter.gettraceback_frame_variables(_request, tb_frame)

  • Returns the filtered dictionary of local variables for the given tracebackframe. By default it replaces the values of sensitive variables with stars(**).

See also

You can also set up custom error reporting by writing a custom piece ofexception middleware. If you do write customerror handling, it’s a good idea to emulate Django’s built-in error handlingand only report/log errors if DEBUG is False.