PageRenderTime 17ms CodeModel.GetById 11ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/django-1.4/docs/howto/error-reporting.txt

https://github.com/Tagtoo/GoogleAppEngine
Plain Text | 277 lines | 202 code | 75 blank | 0 comment | 0 complexity | 20bde7b2cf14f48cd794e88ed09dc901 MD5 | raw file
  1Error reporting
  2===============
  3
  4When 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
  6also prevent malicious users from seeing details of your application that can be
  7revealed by the error pages.
  8
  9However, running with :setting:`DEBUG` set to ``False`` means you'll never see
 10errors generated by your site -- everyone will just see your public error pages.
 11You need to keep track of errors that occur in deployed sites, so Django can be
 12configured to create reports with details about those errors.
 13
 14Email reports
 15-------------
 16
 17Server errors
 18~~~~~~~~~~~~~
 19
 20When :setting:`DEBUG` is ``False``, Django will email the users listed in the
 21:setting:`ADMINS` setting whenever your code raises an unhandled exception and
 22results in an internal server error (HTTP status code 500). This gives the
 23administrators immediate notification of any errors. The :setting:`ADMINS` will
 24get a description of the error, a complete Python traceback, and details about
 25the HTTP request that caused the error.
 26
 27.. note::
 28
 29   In order to send email, Django requires a few settings telling it
 30   how to connect to your mail server. At the very least, you'll need
 31   to specify :setting:`EMAIL_HOST` and possibly
 32   :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD`,
 33   though other settings may be also required depending on your mail
 34   server's configuration. Consult :doc:`the Django settings
 35   documentation </ref/settings>` for a full list of email-related
 36   settings.
 37
 38By default, Django will send email from root@localhost. However, some mail
 39providers reject all email from this address. To use a different sender
 40address, modify the :setting:`SERVER_EMAIL` setting.
 41
 42To disable this behavior, just remove all entries from the :setting:`ADMINS`
 43setting.
 44
 45.. seealso::
 46
 47   .. versionadded:: 1.3
 48
 49   Server error emails are sent using the logging framework, so you can
 50   customize this behavior by :doc:`customizing your logging configuration
 51   </topics/logging>`.
 52
 53404 errors
 54~~~~~~~~~~
 55
 56Django can also be configured to email errors about broken links (404 "page
 57not found" errors). Django sends emails about 404 errors when:
 58
 59* :setting:`DEBUG` is ``False``
 60
 61* :setting:`SEND_BROKEN_LINK_EMAILS` is ``True``
 62
 63* Your :setting:`MIDDLEWARE_CLASSES` setting includes ``CommonMiddleware``
 64  (which it does by default).
 65
 66If those conditions are met, Django will email the users listed in the
 67:setting:`MANAGERS` setting whenever your code raises a 404 and the request has
 68a referer. (It doesn't bother to email for 404s that don't have a referer --
 69those are usually just people typing in broken URLs or broken Web 'bots).
 70
 71You can tell Django to stop reporting particular 404s by tweaking the
 72:setting:`IGNORABLE_404_URLS` setting. It should be a tuple of compiled
 73regular expression objects. For example::
 74
 75    import re
 76    IGNORABLE_404_URLS = (
 77        re.compile(r'\.(php|cgi)$'),
 78        re.compile(r'^/phpmyadmin/'),
 79    )
 80
 81In this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be
 82reported. Neither will any URL starting with ``/phpmyadmin/``.
 83
 84The following example shows how to exclude some conventional URLs that browsers and
 85crawlers often request::
 86
 87    import re
 88    IGNORABLE_404_URLS = (
 89        re.compile(r'^/apple-touch-icon.*\.png$'),
 90        re.compile(r'^/favicon\.ico$'),
 91        re.compile(r'^/robots\.txt$'),
 92    )
 93
 94(Note that these are regular expressions, so we put a backslash in front of
 95periods to escape them.)
 96
 97The best way to disable this behavior is to set
 98:setting:`SEND_BROKEN_LINK_EMAILS` to ``False``.
 99
100.. seealso::
101
102   .. versionadded:: 1.3
103
104   404 errors are logged using the logging framework. By default, these log
105   records are ignored, but you can use them for error reporting by writing a
106   handler and :doc:`configuring logging </topics/logging>` appropriately.
107
108.. seealso::
109
110   .. versionchanged:: 1.4
111
112   Previously, two settings were used to control which URLs not to report:
113   :setting:`IGNORABLE_404_STARTS` and :setting:`IGNORABLE_404_ENDS`. They
114   were replaced by :setting:`IGNORABLE_404_URLS`.
115
116.. _filtering-error-reports:
117
118Filtering error reports
119-----------------------
120
121.. versionadded:: 1.4
122
123Filtering sensitive information
124~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125
126.. currentmodule:: django.views.decorators.debug
127
128Error reports are really helpful for debugging errors, so it is generally
129useful to record as much relevant information about those errors as possible.
130For example, by default Django records the `full traceback`_ for the
131exception raised, each `traceback frame`_'s local variables, and the
132:class:`HttpRequest`'s :ref:`attributes<httprequest-attributes>`.
133
134However, sometimes certain types of information may be too sensitive and thus
135may not be appropriate to be kept track of, for example a user's password or
136credit card number. So Django offers a set of function decorators to help you
137control which information should be filtered out of error reports in a
138production environment (that is, where :setting:`DEBUG` is set to ``False``):
139:func:`sensitive_variables` and :func:`sensitive_post_parameters`.
140
141.. _`full traceback`: http://en.wikipedia.org/wiki/Stack_trace
142.. _`traceback frame`: http://en.wikipedia.org/wiki/Stack_frame
143
144.. function:: sensitive_variables(*variables)
145
146    If a function (either a view or any regular callback) in your code uses
147    local variables susceptible to contain sensitive information, you may
148    prevent the values of those variables from being included in error reports
149    using the ``sensitive_variables`` decorator::
150
151        from django.views.decorators.debug import sensitive_variables
152
153        @sensitive_variables('user', 'pw', 'cc')
154        def process_info(user):
155            pw = user.pass_word
156            cc = user.credit_card_number
157            name = user.name
158            ...
159
160    In the above example, the values for the ``user``, ``pw`` and ``cc``
161    variables will be hidden and replaced with stars (`**********`) in the
162    error reports, whereas the value of the ``name`` variable will be
163    disclosed.
164
165    To systematically hide all local variables of a function from error logs,
166    do not provide any argument to the ``sensitive_variables`` decorator::
167
168        @sensitive_variables()
169        def my_function():
170            ...
171
172.. function:: sensitive_post_parameters(*parameters)
173
174    If one of your views receives an :class:`HttpRequest` object with
175    :attr:`POST parameters<HttpRequest.POST>` susceptible to contain sensitive
176    information, you may prevent the values of those parameters from being
177    included in the error reports using the ``sensitive_post_parameters``
178    decorator::
179
180        from django.views.decorators.debug import sensitive_post_parameters
181
182        @sensitive_post_parameters('pass_word', 'credit_card_number')
183        def record_user_profile(request):
184            UserProfile.create(user=request.user,
185                               password=request.POST['pass_word'],
186                               credit_card=request.POST['credit_card_number'],
187                               name=request.POST['name'])
188            ...
189
190    In the above example, the values for the ``pass_word`` and
191    ``credit_card_number`` POST parameters will be hidden and replaced with
192    stars (`**********`) in the request's representation inside the error
193    reports, whereas the value of the ``name`` parameter will be disclosed.
194
195    To systematically hide all POST parameters of a request in error reports,
196    do not provide any argument to the ``sensitive_post_parameters`` decorator::
197
198        @sensitive_post_parameters()
199        def my_view(request):
200            ...
201
202.. note::
203
204    .. versionchanged:: 1.4
205
206    Since version 1.4, all POST parameters are systematically filtered out of
207    error reports for certain :mod:`contrib.views.auth` views (``login``,
208    ``password_reset_confirm``, ``password_change``, and ``add_view`` and
209    ``user_change_password`` in the ``auth`` admin) to prevent the leaking of
210    sensitive information such as user passwords.
211
212.. _custom-error-reports:
213
214Custom error reports
215~~~~~~~~~~~~~~~~~~~~
216
217All :func:`sensitive_variables` and :func:`sensitive_post_parameters` do is,
218respectively, annotate the decorated function with the names of sensitive
219variables and annotate the ``HttpRequest`` object with the names of sensitive
220POST parameters, so that this sensitive information can later be filtered out
221of reports when an error occurs. The actual filtering is done by Django's
222default error reporter filter:
223:class:`django.views.debug.SafeExceptionReporterFilter`. This filter uses the
224decorators' annotations to replace the corresponding values with stars
225(`**********`) when the error reports are produced. If you wish to override or
226customize this default behavior for your entire site, you need to define your
227own filter class and tell Django to use it via the
228:setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` setting::
229
230    DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'
231
232You may also control in a more granular way which filter to use within any
233given view by setting the ``HttpRequest``'s ``exception_reporter_filter``
234attribute::
235
236    def my_view(request):
237        if request.user.is_authenticated():
238            request.exception_reporter_filter = CustomExceptionReporterFilter()
239        ...
240
241.. currentmodule:: django.views.debug
242
243Your custom filter class needs to inherit from
244:class:`django.views.debug.SafeExceptionReporterFilter` and may override the
245following methods:
246
247.. class:: SafeExceptionReporterFilter
248
249.. method:: SafeExceptionReporterFilter.is_active(self, request)
250
251    Returns ``True`` to activate the filtering operated in the other methods.
252    By default the filter is active if :setting:`DEBUG` is ``False``.
253
254.. method:: SafeExceptionReporterFilter.get_request_repr(self, request)
255
256    Returns the representation string of the request object, that is, the
257    value that would be returned by ``repr(request)``, except it uses the
258    filtered dictionary of POST parameters as determined by
259    :meth:`SafeExceptionReporterFilter.get_post_parameters`.
260
261.. method:: SafeExceptionReporterFilter.get_post_parameters(self, request)
262
263    Returns the filtered dictionary of POST parameters. By default it replaces
264    the values of sensitive parameters with stars (`**********`).
265
266.. method:: SafeExceptionReporterFilter.get_traceback_frame_variables(self, request, tb_frame)
267
268    Returns the filtered dictionary of local variables for the given traceback
269    frame. By default it replaces the values of sensitive variables with stars
270    (`**********`).
271
272.. seealso::
273
274    You can also set up custom error reporting by writing a custom piece of
275    :ref:`exception middleware <exception-middleware>`. If you do write custom
276    error handling, it's a good idea to emulate Django's built-in error handling
277    and only report/log errors if :setting:`DEBUG` is ``False``.