error-reporting.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. Error reporting
  2. ===============
  3. When you're running a public site you should always turn off the
  4. :setting:`DEBUG` setting. That will make your server run much faster, and will
  5. also prevent malicious users from seeing details of your application that can be
  6. revealed by the error pages.
  7. However, running with :setting:`DEBUG` set to ``False`` means you'll never see
  8. errors generated by your site -- everyone will just see your public error pages.
  9. You need to keep track of errors that occur in deployed sites, so Django can be
  10. configured to create reports with details about those errors.
  11. Email reports
  12. -------------
  13. Server errors
  14. ~~~~~~~~~~~~~
  15. When :setting:`DEBUG` is ``False``, Django will email the users listed in the
  16. :setting:`ADMINS` setting whenever your code raises an unhandled exception and
  17. results in an internal server error (HTTP status code 500). This gives the
  18. administrators immediate notification of any errors. The :setting:`ADMINS` will
  19. get a description of the error, a complete Python traceback, and details about
  20. the HTTP request that caused the error.
  21. .. note::
  22. In order to send email, Django requires a few settings telling it
  23. how to connect to your mail server. At the very least, you'll need
  24. to specify :setting:`EMAIL_HOST` and possibly
  25. :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD`,
  26. though other settings may be also required depending on your mail
  27. server's configuration. Consult :doc:`the Django settings
  28. documentation </ref/settings>` for a full list of email-related
  29. settings.
  30. By default, Django will send email from root@localhost. However, some mail
  31. providers reject all email from this address. To use a different sender
  32. address, modify the :setting:`SERVER_EMAIL` setting.
  33. To activate this behavior, put the email addresses of the recipients in the
  34. :setting:`ADMINS` setting.
  35. .. seealso::
  36. Server error emails are sent using the logging framework, so you can
  37. customize this behavior by :doc:`customizing your logging configuration
  38. </topics/logging>`.
  39. 404 errors
  40. ~~~~~~~~~~
  41. Django can also be configured to email errors about broken links (404 "page
  42. not found" errors). Django sends emails about 404 errors when:
  43. * :setting:`DEBUG` is ``False``;
  44. * Your :setting:`MIDDLEWARE_CLASSES` setting includes
  45. :class:`django.middleware.common.BrokenLinkEmailsMiddleware`.
  46. If those conditions are met, Django will email the users listed in the
  47. :setting:`MANAGERS` setting whenever your code raises a 404 and the request has
  48. a referer. (It doesn't bother to email for 404s that don't have a referer --
  49. those are usually just people typing in broken URLs or broken Web 'bots).
  50. .. note::
  51. :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` must appear
  52. before other middleware that intercepts 404 errors, such as
  53. :class:`~django.middleware.locale.LocaleMiddleware` or
  54. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`.
  55. Put it towards the top of your :setting:`MIDDLEWARE_CLASSES` setting.
  56. You can tell Django to stop reporting particular 404s by tweaking the
  57. :setting:`IGNORABLE_404_URLS` setting. It should be a list of compiled
  58. regular expression objects. For example::
  59. import re
  60. IGNORABLE_404_URLS = [
  61. re.compile(r'\.(php|cgi)$'),
  62. re.compile(r'^/phpmyadmin/'),
  63. ]
  64. In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
  65. reported. Neither will any URL starting with ``/phpmyadmin/``.
  66. The following example shows how to exclude some conventional URLs that browsers and
  67. crawlers often request::
  68. import re
  69. IGNORABLE_404_URLS = [
  70. re.compile(r'^/apple-touch-icon.*\.png$'),
  71. re.compile(r'^/favicon\.ico$'),
  72. re.compile(r'^/robots\.txt$'),
  73. ]
  74. (Note that these are regular expressions, so we put a backslash in front of
  75. periods to escape them.)
  76. If you'd like to customize the behavior of
  77. :class:`django.middleware.common.BrokenLinkEmailsMiddleware` further (for
  78. example to ignore requests coming from web crawlers), you should subclass it
  79. and override its methods.
  80. .. seealso::
  81. 404 errors are logged using the logging framework. By default, these log
  82. records are ignored, but you can use them for error reporting by writing a
  83. handler and :doc:`configuring logging </topics/logging>` appropriately.
  84. .. _filtering-error-reports:
  85. Filtering error reports
  86. -----------------------
  87. .. warning::
  88. Filtering sensitive data is a hard problem, and it's nearly impossible to
  89. guarantee that sensitive won't leak into an error report. Therefore, error
  90. reports should only be available to trusted team members and you should
  91. avoid transmitting error reports unencrypted over the Internet (such as
  92. through email).
  93. Filtering sensitive information
  94. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  95. .. currentmodule:: django.views.decorators.debug
  96. Error reports are really helpful for debugging errors, so it is generally
  97. useful to record as much relevant information about those errors as possible.
  98. For example, by default Django records the `full traceback`_ for the
  99. exception raised, each `traceback frame`_’s local variables, and the
  100. :class:`~django.http.HttpRequest`’s :ref:`attributes<httprequest-attributes>`.
  101. However, sometimes certain types of information may be too sensitive and thus
  102. may not be appropriate to be kept track of, for example a user's password or
  103. credit card number. So Django offers a set of function decorators to help you
  104. control which information should be filtered out of error reports in a
  105. production environment (that is, where :setting:`DEBUG` is set to ``False``):
  106. :func:`sensitive_variables` and :func:`sensitive_post_parameters`.
  107. .. _`full traceback`: https://en.wikipedia.org/wiki/Stack_trace
  108. .. _`traceback frame`: https://en.wikipedia.org/wiki/Stack_frame
  109. .. function:: sensitive_variables(*variables)
  110. If a function (either a view or any regular callback) in your code uses
  111. local variables susceptible to contain sensitive information, you may
  112. prevent the values of those variables from being included in error reports
  113. using the ``sensitive_variables`` decorator::
  114. from django.views.decorators.debug import sensitive_variables
  115. @sensitive_variables('user', 'pw', 'cc')
  116. def process_info(user):
  117. pw = user.pass_word
  118. cc = user.credit_card_number
  119. name = user.name
  120. ...
  121. In the above example, the values for the ``user``, ``pw`` and ``cc``
  122. variables will be hidden and replaced with stars (`**********`) in the
  123. error reports, whereas the value of the ``name`` variable will be
  124. disclosed.
  125. To systematically hide all local variables of a function from error logs,
  126. do not provide any argument to the ``sensitive_variables`` decorator::
  127. @sensitive_variables()
  128. def my_function():
  129. ...
  130. .. admonition:: When using multiple decorators
  131. If the variable you want to hide is also a function argument (e.g.
  132. '``user``’ in the following example), and if the decorated function has
  133. multiple decorators, then make sure to place ``@sensitive_variables``
  134. at the top of the decorator chain. This way it will also hide the
  135. function argument as it gets passed through the other decorators::
  136. @sensitive_variables('user', 'pw', 'cc')
  137. @some_decorator
  138. @another_decorator
  139. def process_info(user):
  140. ...
  141. .. function:: sensitive_post_parameters(*parameters)
  142. If one of your views receives an :class:`~django.http.HttpRequest` object
  143. with :attr:`POST parameters<django.http.HttpRequest.POST>` susceptible to
  144. contain sensitive information, you may prevent the values of those
  145. parameters from being included in the error reports using the
  146. ``sensitive_post_parameters`` decorator::
  147. from django.views.decorators.debug import sensitive_post_parameters
  148. @sensitive_post_parameters('pass_word', 'credit_card_number')
  149. def record_user_profile(request):
  150. UserProfile.create(user=request.user,
  151. password=request.POST['pass_word'],
  152. credit_card=request.POST['credit_card_number'],
  153. name=request.POST['name'])
  154. ...
  155. In the above example, the values for the ``pass_word`` and
  156. ``credit_card_number`` POST parameters will be hidden and replaced with
  157. stars (`**********`) in the request's representation inside the error
  158. reports, whereas the value of the ``name`` parameter will be disclosed.
  159. To systematically hide all POST parameters of a request in error reports,
  160. do not provide any argument to the ``sensitive_post_parameters`` decorator::
  161. @sensitive_post_parameters()
  162. def my_view(request):
  163. ...
  164. All POST parameters are systematically filtered out of error reports for
  165. certain :mod:`django.contrib.auth.views` views (``login``,
  166. ``password_reset_confirm``, ``password_change``, and ``add_view`` and
  167. ``user_change_password`` in the ``auth`` admin) to prevent the leaking of
  168. sensitive information such as user passwords.
  169. .. _custom-error-reports:
  170. Custom error reports
  171. ~~~~~~~~~~~~~~~~~~~~
  172. All :func:`sensitive_variables` and :func:`sensitive_post_parameters` do is,
  173. respectively, annotate the decorated function with the names of sensitive
  174. variables and annotate the ``HttpRequest`` object with the names of sensitive
  175. POST parameters, so that this sensitive information can later be filtered out
  176. of reports when an error occurs. The actual filtering is done by Django's
  177. default error reporter filter:
  178. :class:`django.views.debug.SafeExceptionReporterFilter`. This filter uses the
  179. decorators' annotations to replace the corresponding values with stars
  180. (`**********`) when the error reports are produced. If you wish to override or
  181. customize this default behavior for your entire site, you need to define your
  182. own filter class and tell Django to use it via the
  183. :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` setting::
  184. DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'
  185. You may also control in a more granular way which filter to use within any
  186. given view by setting the ``HttpRequest``’s ``exception_reporter_filter``
  187. attribute::
  188. def my_view(request):
  189. if request.user.is_authenticated():
  190. request.exception_reporter_filter = CustomExceptionReporterFilter()
  191. ...
  192. .. currentmodule:: django.views.debug
  193. Your custom filter class needs to inherit from
  194. :class:`django.views.debug.SafeExceptionReporterFilter` and may override the
  195. following methods:
  196. .. class:: SafeExceptionReporterFilter
  197. .. method:: SafeExceptionReporterFilter.is_active(request)
  198. Returns ``True`` to activate the filtering operated in the other methods.
  199. By default the filter is active if :setting:`DEBUG` is ``False``.
  200. .. method:: SafeExceptionReporterFilter.get_post_parameters(request)
  201. Returns the filtered dictionary of POST parameters. By default it replaces
  202. the values of sensitive parameters with stars (`**********`).
  203. .. method:: SafeExceptionReporterFilter.get_traceback_frame_variables(request, tb_frame)
  204. Returns the filtered dictionary of local variables for the given traceback
  205. frame. By default it replaces the values of sensitive variables with stars
  206. (`**********`).
  207. .. seealso::
  208. You can also set up custom error reporting by writing a custom piece of
  209. :ref:`exception middleware <exception-middleware>`. If you do write custom
  210. error handling, it's a good idea to emulate Django's built-in error handling
  211. and only report/log errors if :setting:`DEBUG` is ``False``.