error-reporting.txt 12 KB

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