error-reporting.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. =============================
  2. How to manage 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 instead see your public error
  10. pages. You need to keep track of errors that occur in deployed sites, so Django
  11. can be 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 (strictly speaking, for any response with
  19. an HTTP status code of 500 or greater). This gives the administrators immediate
  20. notification of any errors. The :setting:`ADMINS` will get a description of the
  21. error, a complete Python traceback, and details about the HTTP request that
  22. caused the error.
  23. .. note::
  24. In order to send email, Django requires a few settings telling it
  25. how to connect to your mail server. At the very least, you'll need
  26. to specify :setting:`EMAIL_HOST` and possibly
  27. :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD`,
  28. though other settings may be also required depending on your mail
  29. server's configuration. Consult :doc:`the Django settings
  30. documentation </ref/settings>` for a full list of email-related
  31. settings.
  32. By default, Django will send email from root@localhost. However, some mail
  33. providers reject all email from this address. To use a different sender
  34. address, modify the :setting:`SERVER_EMAIL` setting.
  35. To activate this behavior, put the email addresses of the recipients in the
  36. :setting:`ADMINS` setting.
  37. .. seealso::
  38. Server error emails are sent using the logging framework, so you can
  39. customize this behavior by :doc:`customizing your logging configuration
  40. </topics/logging>`.
  41. 404 errors
  42. ----------
  43. Django can also be configured to email errors about broken links (404 "page
  44. not found" errors). Django sends emails about 404 errors when:
  45. * :setting:`DEBUG` is ``False``;
  46. * Your :setting:`MIDDLEWARE` setting includes
  47. :class:`django.middleware.common.BrokenLinkEmailsMiddleware`.
  48. If those conditions are met, Django will email the users listed in the
  49. :setting:`MANAGERS` setting whenever your code raises a 404 and the request has
  50. a referer. It doesn't bother to email for 404s that don't have a referer --
  51. those are usually people typing in broken URLs or broken web bots. It also
  52. ignores 404s when the referer is equal to the requested URL, since this
  53. behavior is from broken web bots too.
  54. .. note::
  55. :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` must appear
  56. before other middleware that intercepts 404 errors, such as
  57. :class:`~django.middleware.locale.LocaleMiddleware` or
  58. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`.
  59. Put it toward the top of your :setting:`MIDDLEWARE` setting.
  60. You can tell Django to stop reporting particular 404s by tweaking the
  61. :setting:`IGNORABLE_404_URLS` setting. It should be a list of compiled
  62. regular expression objects. For example::
  63. import re
  64. IGNORABLE_404_URLS = [
  65. re.compile(r"\.(php|cgi)$"),
  66. re.compile(r"^/phpmyadmin/"),
  67. ]
  68. In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
  69. reported. Neither will any URL starting with ``/phpmyadmin/``.
  70. The following example shows how to exclude some conventional URLs that browsers and
  71. crawlers often request::
  72. import re
  73. IGNORABLE_404_URLS = [
  74. re.compile(r"^/apple-touch-icon.*\.png$"),
  75. re.compile(r"^/favicon\.ico$"),
  76. re.compile(r"^/robots\.txt$"),
  77. ]
  78. (Note that these are regular expressions, so we put a backslash in front of
  79. periods to escape them.)
  80. If you'd like to customize the behavior of
  81. :class:`django.middleware.common.BrokenLinkEmailsMiddleware` further (for
  82. example to ignore requests coming from web crawlers), you should subclass it
  83. and override its methods.
  84. .. seealso::
  85. 404 errors are logged using the logging framework. By default, these log
  86. records are ignored, but you can use them for error reporting by writing a
  87. handler and :doc:`configuring logging </topics/logging>` appropriately.
  88. .. _filtering-error-reports:
  89. Filtering error reports
  90. =======================
  91. .. warning::
  92. Filtering sensitive data is a hard problem, and it's nearly impossible to
  93. guarantee that sensitive data won't leak into an error report. Therefore,
  94. error reports should only be available to trusted team members and you
  95. should avoid transmitting error reports unencrypted over the internet
  96. (such as through email).
  97. Filtering sensitive information
  98. -------------------------------
  99. .. currentmodule:: django.views.decorators.debug
  100. Error reports are really helpful for debugging errors, so it is generally
  101. useful to record as much relevant information about those errors as possible.
  102. For example, by default Django records the `full traceback`_ for the
  103. exception raised, each `traceback frame`_’s local variables, and the
  104. :class:`~django.http.HttpRequest`’s :ref:`attributes<httprequest-attributes>`.
  105. However, sometimes certain types of information may be too sensitive and thus
  106. may not be appropriate to be kept track of, for example a user's password or
  107. credit card number. So in addition to filtering out settings that appear to be
  108. sensitive as described in the :setting:`DEBUG` documentation, Django offers a
  109. set of function decorators to help you control which information should be
  110. filtered out of error reports in a production environment (that is, where
  111. :setting:`DEBUG` is set to ``False``): :func:`sensitive_variables` and
  112. :func:`sensitive_post_parameters`.
  113. .. _`full traceback`: https://en.wikipedia.org/wiki/Stack_trace
  114. .. _`traceback frame`: https://en.wikipedia.org/wiki/Stack_frame
  115. .. function:: sensitive_variables(*variables)
  116. If a function (either a view or any regular callback) in your code uses
  117. local variables susceptible to contain sensitive information, you may
  118. prevent the values of those variables from being included in error reports
  119. using the ``sensitive_variables`` decorator::
  120. from django.views.decorators.debug import sensitive_variables
  121. @sensitive_variables("user", "pw", "cc")
  122. def process_info(user):
  123. pw = user.pass_word
  124. cc = user.credit_card_number
  125. name = user.name
  126. ...
  127. In the above example, the values for the ``user``, ``pw`` and ``cc``
  128. variables will be hidden and replaced with stars (``**********``)
  129. in the error reports, whereas the value of the ``name`` variable will be
  130. disclosed.
  131. To systematically hide all local variables of a function from error logs,
  132. do not provide any argument to the ``sensitive_variables`` decorator::
  133. @sensitive_variables()
  134. def my_function(): ...
  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. .. versionchanged:: 5.0
  146. Support for wrapping ``async`` functions was added.
  147. .. function:: sensitive_post_parameters(*parameters)
  148. If one of your views receives an :class:`~django.http.HttpRequest` object
  149. with :attr:`POST parameters<django.http.HttpRequest.POST>` susceptible to
  150. contain sensitive information, you may prevent the values of those
  151. parameters from being included in the error reports using the
  152. ``sensitive_post_parameters`` decorator::
  153. from django.views.decorators.debug import sensitive_post_parameters
  154. @sensitive_post_parameters("pass_word", "credit_card_number")
  155. def record_user_profile(request):
  156. UserProfile.create(
  157. user=request.user,
  158. password=request.POST["pass_word"],
  159. credit_card=request.POST["credit_card_number"],
  160. name=request.POST["name"],
  161. )
  162. ...
  163. In the above example, the values for the ``pass_word`` and
  164. ``credit_card_number`` POST parameters will be hidden and replaced with
  165. stars (``**********``) in the request's representation inside the
  166. error reports, whereas the value of the ``name`` parameter will be
  167. disclosed.
  168. To systematically hide all POST parameters of a request in error reports,
  169. do not provide any argument to the ``sensitive_post_parameters`` decorator::
  170. @sensitive_post_parameters()
  171. def my_view(request): ...
  172. All POST parameters are systematically filtered out of error reports for
  173. certain :mod:`django.contrib.auth.views` views (``login``,
  174. ``password_reset_confirm``, ``password_change``, and ``add_view`` and
  175. ``user_change_password`` in the ``auth`` admin) to prevent the leaking of
  176. sensitive information such as user passwords.
  177. .. versionchanged:: 5.0
  178. Support for wrapping ``async`` functions was added.
  179. .. _custom-error-reports:
  180. Custom error reports
  181. --------------------
  182. All :func:`sensitive_variables` and :func:`sensitive_post_parameters` do is,
  183. respectively, annotate the decorated function with the names of sensitive
  184. variables and annotate the ``HttpRequest`` object with the names of sensitive
  185. POST parameters, so that this sensitive information can later be filtered out
  186. of reports when an error occurs. The actual filtering is done by Django's
  187. default error reporter filter:
  188. :class:`django.views.debug.SafeExceptionReporterFilter`. This filter uses the
  189. decorators' annotations to replace the corresponding values with stars
  190. (``**********``) when the error reports are produced. If you wish to
  191. override or customize this default behavior for your entire site, you need to
  192. define your own filter class and tell Django to use it via the
  193. :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` setting::
  194. DEFAULT_EXCEPTION_REPORTER_FILTER = "path.to.your.CustomExceptionReporterFilter"
  195. You may also control in a more granular way which filter to use within any
  196. given view by setting the ``HttpRequest``’s ``exception_reporter_filter``
  197. attribute::
  198. def my_view(request):
  199. if request.user.is_authenticated:
  200. request.exception_reporter_filter = CustomExceptionReporterFilter()
  201. ...
  202. .. currentmodule:: django.views.debug
  203. Your custom filter class needs to inherit from
  204. :class:`django.views.debug.SafeExceptionReporterFilter` and may override the
  205. following attributes and methods:
  206. .. class:: SafeExceptionReporterFilter
  207. .. attribute:: cleansed_substitute
  208. The string value to replace sensitive value with. By default it
  209. replaces the values of sensitive variables with stars
  210. (``**********``).
  211. .. attribute:: hidden_settings
  212. A compiled regular expression object used to match settings and
  213. ``request.META`` values considered as sensitive. By default equivalent
  214. to::
  215. import re
  216. re.compile(r"API|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flags=re.IGNORECASE)
  217. .. versionchanged:: 4.2
  218. ``HTTP_COOKIE`` was added.
  219. .. method:: is_active(request)
  220. Returns ``True`` to activate the filtering in
  221. :meth:`get_post_parameters` and :meth:`get_traceback_frame_variables`.
  222. By default the filter is active if :setting:`DEBUG` is ``False``. Note
  223. that sensitive ``request.META`` values are always filtered along with
  224. sensitive setting values, as described in the :setting:`DEBUG`
  225. documentation.
  226. .. method:: get_post_parameters(request)
  227. Returns the filtered dictionary of POST parameters. Sensitive values
  228. are replaced with :attr:`cleansed_substitute`.
  229. .. method:: get_traceback_frame_variables(request, tb_frame)
  230. Returns the filtered dictionary of local variables for the given
  231. traceback frame. Sensitive values are replaced with
  232. :attr:`cleansed_substitute`.
  233. If you need to customize error reports beyond filtering you may specify a
  234. custom error reporter class by defining the
  235. :setting:`DEFAULT_EXCEPTION_REPORTER` setting::
  236. DEFAULT_EXCEPTION_REPORTER = "path.to.your.CustomExceptionReporter"
  237. The exception reporter is responsible for compiling the exception report data,
  238. and formatting it as text or HTML appropriately. (The exception reporter uses
  239. :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` when preparing the exception
  240. report data.)
  241. Your custom reporter class needs to inherit from
  242. :class:`django.views.debug.ExceptionReporter`.
  243. .. class:: ExceptionReporter
  244. .. attribute:: html_template_path
  245. Property that returns a :class:`pathlib.Path` representing the absolute
  246. filesystem path to a template for rendering the HTML representation of
  247. the exception. Defaults to the Django provided template.
  248. .. attribute:: text_template_path
  249. Property that returns a :class:`pathlib.Path` representing the absolute
  250. filesystem path to a template for rendering the plain-text
  251. representation of the exception. Defaults to the Django provided
  252. template.
  253. .. method:: get_traceback_data()
  254. Return a dictionary containing traceback information.
  255. This is the main extension point for customizing exception reports, for
  256. example::
  257. from django.views.debug import ExceptionReporter
  258. class CustomExceptionReporter(ExceptionReporter):
  259. def get_traceback_data(self):
  260. data = super().get_traceback_data()
  261. # ... remove/add something here ...
  262. return data
  263. .. method:: get_traceback_html()
  264. Return HTML version of exception report.
  265. Used for HTML version of debug 500 HTTP error page.
  266. .. method:: get_traceback_text()
  267. Return plain text version of exception report.
  268. Used for plain text version of debug 500 HTTP error page and email
  269. reports.
  270. As with the filter class, you may control which exception reporter class to use
  271. within any given view by setting the ``HttpRequest``’s
  272. ``exception_reporter_class`` attribute::
  273. def my_view(request):
  274. if request.user.is_authenticated:
  275. request.exception_reporter_class = CustomExceptionReporter()
  276. ...
  277. .. seealso::
  278. You can also set up custom error reporting by writing a custom piece of
  279. :ref:`exception middleware <exception-middleware>`. If you do write custom
  280. error handling, it's a good idea to emulate Django's built-in error handling
  281. and only report/log errors if :setting:`DEBUG` is ``False``.