Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Error reporting


May 14, 2021 Django


Table of contents


Error reporting

The DEBUG setting should always be turned off when running a public site. This will make your server run faster and prevent malicious users from viewing application details that might appear on the error page.

However, DEBUG running set as False means that you will never see the error generated by the site - everyone will see your public error page. You need to track errors that occur at the deployment site, so you can configure Django to create a report that contains detailed information about those errors.

E-mail report

The server is wrong

When DEBUGis is False, ADMINS sends an e-mail message to the users listed in the settings as long as your code throws an unprocessed exception and causes an internal server error (strictly speaking, any response with http status code 500 or higher). T his gives the administrator immediate notification of any errors. The ADMINS will get an incorrect description, a complete Python trace, and more information about the HTTP request that caused the error.

Note: In order to send e-mail, Django needs some settings to tell it how to connect to your mail server. A t a minimum, you need to specify EMAIL_HOST and may require EMAIL_HOST_USER and EMAIL_HOST_PASSWORD, although additional settings may be required depending on the configuration of your mail server. For a complete list of email-related settings, see the Django settings documentation.

By default, Django sends an e-mail message via root s.localhost. H owever, some mail providers reject all e-mail messages from that address. To use a different sender address, modify SERVER_EMAIL settings.

To activate this behavior, place the recipient's email address in the ADMINS settings.

You can also take a look

Server error e-mail messages are sent using the logging framework, so you can customize this behavior by customizing the logging configuration.

404 error

Django can also be configured to email an error about breaking a link (404 "Page not found" error). Django sends an email about the 404 error if:

  • DEBUG is False;
  • Your MIDLEWARE settings include django.middleware.common.brokenLinkEmailsMidleware.

If these conditions are met, Django e-mails the users listed in the settings to you as long as your code raises 404 and the request has a referral source. D on't email 404 without a referrer, who is usually the one who enters a corrupted URL or a corrupted Web bot. When the referencer is equal to the requested URL, it also ignores 404 because the behavior also comes from a corrupted Web bot.

Note: B rokenLink Emails Middleware must appear before blocking other middleware for 404 errors, such as LocaleMiddleware or FlatpageFallback Midleware. Place it at the top of the MIDLEWARE setting.

You can IGNORABLE_404_URLS Django to stop reporting specific 404 by adjusting the settings. I t should be a list of compiled regular expression objects. For example:

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

In this example, any 404 .php URL ending in a .cgi will not be reported. The URL that starts will not / phpmyadmin / .

The following example shows how to exclude some of the regular URLs frequently requested by browsers and searchers:

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

(Note that these are regular expressions, so we add a backslash before the period to escape them.)

If you want to further customize the behavior (such as ignoring requests from a Web crawler), you should subsyscize it and override its methods.

You can also take a look

Use the logging framework to log 404 errors. By default, these logs are ignored, but you can use them for error reporting by writing handlers and configuring them appropriately.

Filter error reports

Warning: Filtering sensitive data is a challenge, and it is almost impossible to guarantee that sensitive data will not leak into error reports. Therefore, error reports should only be made available to trusted team members, and you should avoid transmitting unencrypted error reports over the Internet, such as via e-mail.

Filter sensitive information

Error reporting is really helpful for debugging errors, so it's often useful to record as much information about them as possible. For example, by default, Django records the full trace of the exception thrown, the local variables of each trace frame, and the properties of HttpRequest.

However, sometimes certain types of information may be too sensitive and may not be appropriate for tracking, such as a user's password or credit card number. Therefore, in addition to filtering out seemingly sensitive settings as described in the DEBUG documentation, Django provides a set of function decorators to help you control what information should be filtered out from error reports in the production environment (i.e., where DEBUG is set to False): sensitive_variables() and sensitive_post_parameters ().

sensitive_variables variable )

If the functions in your code (views or any regular callbacks) use local variables that are easy sensitive_variables decorator to prevent the values of those variables from being included in the error report:

from django.views.decorators.debug import sensitive_variables

@sensitive_variables('user', 'pw', 'cc')
def process_info(user):
    pw = user.pass_word
    cc = user.credit_card_number
    name = user.name
    ...

In the example above, the user pw cc this value are hidden and the error is reported with a star ********** the value name name is exposed.

To systematically hide all local variables of a function from the error log, do not sensitive_variables the adornor:

@sensitive_variables()
def my_function():
    ...

When using more than one decorator

The variable you want to hide is also a user in the following example), and if the decorated function has more than one modifier, be sure @sensitive_variables the top of the modifier chain. This way, when it is passed through other decorators, it also hides function parameters:

@sensitive_variables('user', 'pw', 'cc')
@some_decorator
@another_decorator
def process_info(user):
    ...
sensitive_post_parameters * parameters

If one of your views receives an HttpRequest object that is HttpRequest you can use the decorator to prevent the values of these parameters from being included in sensitive_post_parameters POST parameters sensitive_post_parameters

from django.views.decorators.debug import sensitive_post_parameters

@sensitive_post_parameters('pass_word', 'credit_card_number')
def record_user_profile(request):
    UserProfile.create(
        user=request.user,
        password=request.POST['pass_word'],
        credit_card=request.POST['credit_card_number'],
        name=request.POST['name'],
    )
    ...

In the example above, in the request represented in the error report, pass_word credit_card_number pass_word and credit_card_number parameters are hidden and replaced with an ********** the value of the name parameter is exposed.

To systematically hide all requested POST parameters in error reports, do not sensitive_post_parameters to the adornor:

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

Some errors that are filtered by the system for all POST parameters are reported django.contrib.auth.views times login password_reset_confirm password_change add_view and user_change_password auth to prevent sensitive information from leaking such as user passwords. user_change_password

Custom error reporting

All sensitive_variables() and sensitive_post_parameters() do comment the decorated function with the name of the sensitive variable, respectively, and HttpRequest comments the object with the name of the sensitive POST parameter so that this sensitive information can be filtered out of the report later in the event of an error. T he actual filtering is done by Django.views.debug.SafeExceptionReporterFilter by Django's default error report filter. W hen an error report is generated, this filter replaces the value with star() with a comment from the modifier. If you want to override or customize this default behavior for the entire site, you need to define your own filter class and tell Django to use it DEFAULT_EXCEPTION_REPORTER_FILTER the following settings:

DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'

You can also control the filters to be used in exception_reporter_filter any given view in a more granular way by setting httpRequest's property:

def my_view(request):
    if request.user.is_authenticated:
        request.exception_reporter_filter = CustomExceptionReporterFilter()
    ...

Your custom filter class needs to inherit django.views.debug.SafeExceptionReporterFilter and can override the following methods:

Class SafeExceptionReporterFilter
SafeExceptionReporterFilter. is_active ( Request )

Return True activate filtering for operations in other methods. By default, DEBUG is, the filter is active False

SafeExceptionReporterFilter. get_post_parameters ( Request )

Returns the filtered POST parameter dictionary. By default, it replaces the value of sensitive parameters **********

SafeExceptionReporterFilter. get_traceback_frame_variables request tb_frame

A filter dictionary that returns local variables for a given backtracking frame. By default, it replaces the value of **********

You can also take a look

You can also set up custom error reports by writing custom exception middleware. If you do write custom error handling, it's a good idea to simulate Django's built-in error handling, and if DEBUG is, report/record only errors.

For more information: https://docs.djangoproject.com/en/3.0/