logging.txt 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. =======
  2. Logging
  3. =======
  4. .. module:: django.utils.log
  5. :synopsis: Logging tools for Django applications
  6. A quick logging primer
  7. ======================
  8. Django uses Python's builtin :mod:`logging` module to perform system logging.
  9. The usage of this module is discussed in detail in Python's own documentation.
  10. However, if you've never used Python's logging framework (or even if you have),
  11. here's a quick primer.
  12. The cast of players
  13. -------------------
  14. A Python logging configuration consists of four parts:
  15. * :ref:`topic-logging-parts-loggers`
  16. * :ref:`topic-logging-parts-handlers`
  17. * :ref:`topic-logging-parts-filters`
  18. * :ref:`topic-logging-parts-formatters`
  19. .. _topic-logging-parts-loggers:
  20. Loggers
  21. ~~~~~~~
  22. A logger is the entry point into the logging system. Each logger is
  23. a named bucket to which messages can be written for processing.
  24. A logger is configured to have a *log level*. This log level describes
  25. the severity of the messages that the logger will handle. Python
  26. defines the following log levels:
  27. * ``DEBUG``: Low level system information for debugging purposes
  28. * ``INFO``: General system information
  29. * ``WARNING``: Information describing a minor problem that has
  30. occurred.
  31. * ``ERROR``: Information describing a major problem that has
  32. occurred.
  33. * ``CRITICAL``: Information describing a critical problem that has
  34. occurred.
  35. Each message that is written to the logger is a *Log Record*. Each log
  36. record also has a *log level* indicating the severity of that specific
  37. message. A log record can also contain useful metadata that describes
  38. the event that is being logged. This can include details such as a
  39. stack trace or an error code.
  40. When a message is given to the logger, the log level of the message is
  41. compared to the log level of the logger. If the log level of the
  42. message meets or exceeds the log level of the logger itself, the
  43. message will undergo further processing. If it doesn't, the message
  44. will be ignored.
  45. Once a logger has determined that a message needs to be processed,
  46. it is passed to a *Handler*.
  47. .. _topic-logging-parts-handlers:
  48. Handlers
  49. ~~~~~~~~
  50. The handler is the engine that determines what happens to each message
  51. in a logger. It describes a particular logging behavior, such as
  52. writing a message to the screen, to a file, or to a network socket.
  53. Like loggers, handlers also have a log level. If the log level of a
  54. log record doesn't meet or exceed the level of the handler, the
  55. handler will ignore the message.
  56. A logger can have multiple handlers, and each handler can have a
  57. different log level. In this way, it is possible to provide different
  58. forms of notification depending on the importance of a message. For
  59. example, you could install one handler that forwards ``ERROR`` and
  60. ``CRITICAL`` messages to a paging service, while a second handler
  61. logs all messages (including ``ERROR`` and ``CRITICAL`` messages) to a
  62. file for later analysis.
  63. .. _topic-logging-parts-filters:
  64. Filters
  65. ~~~~~~~
  66. A filter is used to provide additional control over which log records
  67. are passed from logger to handler.
  68. By default, any log message that meets log level requirements will be
  69. handled. However, by installing a filter, you can place additional
  70. criteria on the logging process. For example, you could install a
  71. filter that only allows ``ERROR`` messages from a particular source to
  72. be emitted.
  73. Filters can also be used to modify the logging record prior to being
  74. emitted. For example, you could write a filter that downgrades
  75. ``ERROR`` log records to ``WARNING`` records if a particular set of
  76. criteria are met.
  77. Filters can be installed on loggers or on handlers; multiple filters
  78. can be used in a chain to perform multiple filtering actions.
  79. .. _topic-logging-parts-formatters:
  80. Formatters
  81. ~~~~~~~~~~
  82. Ultimately, a log record needs to be rendered as text. Formatters
  83. describe the exact format of that text. A formatter usually consists
  84. of a Python formatting string containing
  85. :ref:`LogRecord attributes <python:logrecord-attributes>`; however,
  86. you can also write custom formatters to implement specific formatting behavior.
  87. Using logging
  88. =============
  89. Once you have configured your loggers, handlers, filters and
  90. formatters, you need to place logging calls into your code. Using the
  91. logging framework is very simple. Here's an example::
  92. # import the logging library
  93. import logging
  94. # Get an instance of a logger
  95. logger = logging.getLogger(__name__)
  96. def my_view(request, arg1, arg):
  97. ...
  98. if bad_mojo:
  99. # Log an error message
  100. logger.error('Something went wrong!')
  101. And that's it! Every time the ``bad_mojo`` condition is activated, an
  102. error log record will be written.
  103. Naming loggers
  104. --------------
  105. The call to :func:`logging.getLogger()` obtains (creating, if
  106. necessary) an instance of a logger. The logger instance is identified
  107. by a name. This name is used to identify the logger for configuration
  108. purposes.
  109. By convention, the logger name is usually ``__name__``, the name of
  110. the Python module that contains the logger. This allows you to filter
  111. and handle logging calls on a per-module basis. However, if you have
  112. some other way of organizing your logging messages, you can provide
  113. any dot-separated name to identify your logger::
  114. # Get an instance of a specific named logger
  115. logger = logging.getLogger('project.interesting.stuff')
  116. The dotted paths of logger names define a hierarchy. The
  117. ``project.interesting`` logger is considered to be a parent of the
  118. ``project.interesting.stuff`` logger; the ``project`` logger
  119. is a parent of the ``project.interesting`` logger.
  120. Why is the hierarchy important? Well, because loggers can be set to
  121. *propagate* their logging calls to their parents. In this way, you can
  122. define a single set of handlers at the root of a logger tree, and
  123. capture all logging calls in the subtree of loggers. A logging handler
  124. defined in the ``project`` namespace will catch all logging messages
  125. issued on the ``project.interesting`` and
  126. ``project.interesting.stuff`` loggers.
  127. This propagation can be controlled on a per-logger basis. If
  128. you don't want a particular logger to propagate to its parents, you
  129. can turn off this behavior.
  130. Making logging calls
  131. --------------------
  132. The logger instance contains an entry method for each of the default
  133. log levels:
  134. * ``logger.debug()``
  135. * ``logger.info()``
  136. * ``logger.warning()``
  137. * ``logger.error()``
  138. * ``logger.critical()``
  139. There are two other logging calls available:
  140. * ``logger.log()``: Manually emits a logging message with a
  141. specific log level.
  142. * ``logger.exception()``: Creates an ``ERROR`` level logging
  143. message wrapping the current exception stack frame.
  144. .. _configuring-logging:
  145. Configuring logging
  146. ===================
  147. Of course, it isn't enough to just put logging calls into your code.
  148. You also need to configure the loggers, handlers, filters and
  149. formatters to ensure that logging output is output in a useful way.
  150. Python's logging library provides several techniques to configure
  151. logging, ranging from a programmatic interface to configuration files.
  152. By default, Django uses the :ref:`dictConfig format
  153. <logging-config-dictschema>`.
  154. In order to configure logging, you use :setting:`LOGGING` to define a
  155. dictionary of logging settings. These settings describes the loggers,
  156. handlers, filters and formatters that you want in your logging setup,
  157. and the log levels and other properties that you want those components
  158. to have.
  159. By default, the :setting:`LOGGING` setting is merged with :ref:`Django's
  160. default logging configuration <default-logging-configuration>` using the
  161. following scheme.
  162. If the ``disable_existing_loggers`` key in the :setting:`LOGGING` dictConfig is
  163. set to ``True`` (which is the default) then all loggers from the default
  164. configuration will be disabled. Disabled loggers are not the same as removed;
  165. the logger will still exist, but will silently discard anything logged to it,
  166. not even propagating entries to a parent logger. Thus you should be very
  167. careful using ``'disable_existing_loggers': True``; it's probably not what you
  168. want. Instead, you can set ``disable_existing_loggers`` to ``False`` and
  169. redefine some or all of the default loggers; or you can set
  170. :setting:`LOGGING_CONFIG` to ``None`` and :ref:`handle logging config yourself
  171. <disabling-logging-configuration>`.
  172. Logging is configured as part of the general Django ``setup()`` function.
  173. Therefore, you can be certain that loggers are always ready for use in your
  174. project code.
  175. Examples
  176. --------
  177. The full documentation for :ref:`dictConfig format <logging-config-dictschema>`
  178. is the best source of information about logging configuration dictionaries.
  179. However, to give you a taste of what is possible, here are several examples.
  180. First, here's a simple configuration which writes all logging from the
  181. :ref:`django-logger` logger to a local file::
  182. .. code-block:: python
  183. :caption: settings.py
  184. LOGGING = {
  185. 'version': 1,
  186. 'disable_existing_loggers': False,
  187. 'handlers': {
  188. 'file': {
  189. 'level': 'DEBUG',
  190. 'class': 'logging.FileHandler',
  191. 'filename': '/path/to/django/debug.log',
  192. },
  193. },
  194. 'loggers': {
  195. 'django': {
  196. 'handlers': ['file'],
  197. 'level': 'DEBUG',
  198. 'propagate': True,
  199. },
  200. },
  201. }
  202. If you use this example, be sure to change the ``'filename'`` path to a
  203. location that's writable by the user that's running the Django application.
  204. Second, here's an example of how to make the logging system print Django's
  205. logging to the console. It may be useful during local development.
  206. By default, this config only sends messages of level ``INFO`` or higher to the
  207. console (same as Django's default logging config, except that the default only
  208. displays log records when ``DEBUG=True``). Django does not log many such
  209. messages. With this config, however, you can also set the environment variable
  210. ``DJANGO_LOG_LEVEL=DEBUG`` to see all of Django's debug logging which is very
  211. verbose as it includes all database queries::
  212. .. code-block:: python
  213. :caption: settings.py
  214. import os
  215. LOGGING = {
  216. 'version': 1,
  217. 'disable_existing_loggers': False,
  218. 'handlers': {
  219. 'console': {
  220. 'class': 'logging.StreamHandler',
  221. },
  222. },
  223. 'loggers': {
  224. 'django': {
  225. 'handlers': ['console'],
  226. 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
  227. },
  228. },
  229. }
  230. Finally, here's an example of a fairly complex logging setup::
  231. .. code-block:: python
  232. :caption: settings.py
  233. LOGGING = {
  234. 'version': 1,
  235. 'disable_existing_loggers': False,
  236. 'formatters': {
  237. 'verbose': {
  238. 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
  239. 'style': '{',
  240. },
  241. 'simple': {
  242. 'format': '{levelname} {message}',
  243. 'style': '{',
  244. },
  245. },
  246. 'filters': {
  247. 'special': {
  248. '()': 'project.logging.SpecialFilter',
  249. 'foo': 'bar',
  250. },
  251. 'require_debug_true': {
  252. '()': 'django.utils.log.RequireDebugTrue',
  253. },
  254. },
  255. 'handlers': {
  256. 'console': {
  257. 'level': 'INFO',
  258. 'filters': ['require_debug_true'],
  259. 'class': 'logging.StreamHandler',
  260. 'formatter': 'simple'
  261. },
  262. 'mail_admins': {
  263. 'level': 'ERROR',
  264. 'class': 'django.utils.log.AdminEmailHandler',
  265. 'filters': ['special']
  266. }
  267. },
  268. 'loggers': {
  269. 'django': {
  270. 'handlers': ['console'],
  271. 'propagate': True,
  272. },
  273. 'django.request': {
  274. 'handlers': ['mail_admins'],
  275. 'level': 'ERROR',
  276. 'propagate': False,
  277. },
  278. 'myproject.custom': {
  279. 'handlers': ['console', 'mail_admins'],
  280. 'level': 'INFO',
  281. 'filters': ['special']
  282. }
  283. }
  284. }
  285. This logging configuration does the following things:
  286. * Identifies the configuration as being in 'dictConfig version 1'
  287. format. At present, this is the only dictConfig format version.
  288. * Defines two formatters:
  289. * ``simple``, that just outputs the log level name (e.g.,
  290. ``DEBUG``) and the log message.
  291. The ``format`` string is a normal Python formatting string
  292. describing the details that are to be output on each logging
  293. line. The full list of detail that can be output can be
  294. found in :ref:`formatter-objects`.
  295. * ``verbose``, that outputs the log level name, the log
  296. message, plus the time, process, thread and module that
  297. generate the log message.
  298. * Defines two filters:
  299. * ``project.logging.SpecialFilter``, using the alias ``special``. If this
  300. filter required additional arguments, they can be provided as additional
  301. keys in the filter configuration dictionary. In this case, the argument
  302. ``foo`` will be given a value of ``bar`` when instantiating
  303. ``SpecialFilter``.
  304. * ``django.utils.log.RequireDebugTrue``, which passes on records when
  305. :setting:`DEBUG` is ``True``.
  306. * Defines two handlers:
  307. * ``console``, a :class:`~logging.StreamHandler`, which prints any ``INFO``
  308. (or higher) message to ``sys.stderr``. This handler uses the ``simple``
  309. output format.
  310. * ``mail_admins``, an :class:`AdminEmailHandler`, which emails any ``ERROR``
  311. (or higher) message to the site :setting:`ADMINS`. This handler uses the
  312. ``special`` filter.
  313. * Configures three loggers:
  314. * ``django``, which passes all messages to the ``console`` handler.
  315. * ``django.request``, which passes all ``ERROR`` messages to
  316. the ``mail_admins`` handler. In addition, this logger is
  317. marked to *not* propagate messages. This means that log
  318. messages written to ``django.request`` will not be handled
  319. by the ``django`` logger.
  320. * ``myproject.custom``, which passes all messages at ``INFO``
  321. or higher that also pass the ``special`` filter to two
  322. handlers -- the ``console``, and ``mail_admins``. This
  323. means that all ``INFO`` level messages (or higher) will be
  324. printed to the console; ``ERROR`` and ``CRITICAL``
  325. messages will also be output via email.
  326. Custom logging configuration
  327. ----------------------------
  328. If you don't want to use Python's dictConfig format to configure your
  329. logger, you can specify your own configuration scheme.
  330. The :setting:`LOGGING_CONFIG` setting defines the callable that will
  331. be used to configure Django's loggers. By default, it points at
  332. Python's :func:`logging.config.dictConfig()` function. However, if you want to
  333. use a different configuration process, you can use any other callable
  334. that takes a single argument. The contents of :setting:`LOGGING` will
  335. be provided as the value of that argument when logging is configured.
  336. .. _disabling-logging-configuration:
  337. Disabling logging configuration
  338. -------------------------------
  339. If you don't want to configure logging at all (or you want to manually
  340. configure logging using your own approach), you can set
  341. :setting:`LOGGING_CONFIG` to ``None``. This will disable the
  342. configuration process for :ref:`Django's default logging
  343. <default-logging-configuration>`. Here's an example that disables Django's
  344. logging configuration and then manually configures logging:
  345. .. code-block:: python
  346. :caption: settings.py
  347. LOGGING_CONFIG = None
  348. import logging.config
  349. logging.config.dictConfig(...)
  350. Setting :setting:`LOGGING_CONFIG` to ``None`` only means that the automatic
  351. configuration process is disabled, not logging itself. If you disable the
  352. configuration process, Django will still make logging calls, falling back to
  353. whatever default logging behavior is defined.
  354. Django's logging extensions
  355. ===========================
  356. Django provides a number of utilities to handle the unique
  357. requirements of logging in Web server environment.
  358. Loggers
  359. -------
  360. Django provides several built-in loggers.
  361. .. _django-logger:
  362. ``django``
  363. ~~~~~~~~~~
  364. The catch-all logger for messages in the ``django`` hierarchy. No messages are
  365. posted using this name but instead using one of the loggers below.
  366. .. _django-request-logger:
  367. ``django.request``
  368. ~~~~~~~~~~~~~~~~~~
  369. Log messages related to the handling of requests. 5XX responses are
  370. raised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``
  371. messages. Requests that are logged to the ``django.security`` logger aren't
  372. logged to ``django.request``.
  373. Messages to this logger have the following extra context:
  374. * ``status_code``: The HTTP response code associated with the
  375. request.
  376. * ``request``: The request object that generated the logging
  377. message.
  378. .. _django-server-logger:
  379. ``django.server``
  380. ~~~~~~~~~~~~~~~~~
  381. Log messages related to the handling of requests received by the server invoked
  382. by the :djadmin:`runserver` command. HTTP 5XX responses are logged as ``ERROR``
  383. messages, 4XX responses are logged as ``WARNING`` messages, and everything else
  384. is logged as ``INFO``.
  385. Messages to this logger have the following extra context:
  386. * ``status_code``: The HTTP response code associated with the request.
  387. * ``request``: The request object that generated the logging message.
  388. .. _django-template-logger:
  389. ``django.template``
  390. ~~~~~~~~~~~~~~~~~~~
  391. Log messages related to the rendering of templates.
  392. * Missing context variables are logged as ``DEBUG`` messages.
  393. .. _django-db-logger:
  394. ``django.db.backends``
  395. ~~~~~~~~~~~~~~~~~~~~~~
  396. Messages relating to the interaction of code with the database. For example,
  397. every application-level SQL statement executed by a request is logged at the
  398. ``DEBUG`` level to this logger.
  399. Messages to this logger have the following extra context:
  400. * ``duration``: The time taken to execute the SQL statement.
  401. * ``sql``: The SQL statement that was executed.
  402. * ``params``: The parameters that were used in the SQL call.
  403. For performance reasons, SQL logging is only enabled when
  404. ``settings.DEBUG`` is set to ``True``, regardless of the logging
  405. level or handlers that are installed.
  406. This logging does not include framework-level initialization (e.g.
  407. ``SET TIMEZONE``) or transaction management queries (e.g. ``BEGIN``,
  408. ``COMMIT``, and ``ROLLBACK``). Turn on query logging in your database if you
  409. wish to view all database queries.
  410. .. _django-security-logger:
  411. ``django.security.*``
  412. ~~~~~~~~~~~~~~~~~~~~~~
  413. The security loggers will receive messages on any occurrence of
  414. :exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
  415. errors. There is a sub-logger for each subtype of security error, including all
  416. ``SuspiciousOperation``\s. The level of the log event depends on where the
  417. exception is handled. Most occurrences are logged as a warning, while
  418. any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
  419. error. For example, when an HTTP ``Host`` header is included in a request from
  420. a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
  421. response, and an error message will be logged to the
  422. ``django.security.DisallowedHost`` logger.
  423. These log events will reach the ``django`` logger by default, which mails error
  424. events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
  425. to a ``SuspiciousOperation`` will not be logged to the ``django.request``
  426. logger, but only to the ``django.security`` logger.
  427. To silence a particular type of ``SuspiciousOperation``, you can override that
  428. specific logger following this example:
  429. .. code-block:: python
  430. 'handlers': {
  431. 'null': {
  432. 'class': 'logging.NullHandler',
  433. },
  434. },
  435. 'loggers': {
  436. 'django.security.DisallowedHost': {
  437. 'handlers': ['null'],
  438. 'propagate': False,
  439. },
  440. },
  441. Other ``django.security`` loggers not based on ``SuspiciousOperation`` are:
  442. * ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.
  443. ``django.db.backends.schema``
  444. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  445. Logs the SQL queries that are executed during schema changes to the database by
  446. the :doc:`migrations framework </topics/migrations>`. Note that it won't log the
  447. queries executed by :class:`~django.db.migrations.operations.RunPython`.
  448. Messages to this logger have ``params`` and ``sql`` in their extra context (but
  449. unlike ``django.db.backends``, not duration). The values have the same meaning
  450. as explained in :ref:`django-db-logger`.
  451. Handlers
  452. --------
  453. Django provides one log handler in addition to those provided by the
  454. Python logging module.
  455. .. class:: AdminEmailHandler(include_html=False, email_backend=None)
  456. This handler sends an email to the site :setting:`ADMINS` for each log
  457. message it receives.
  458. If the log record contains a ``request`` attribute, the full details
  459. of the request will be included in the email. The email subject will
  460. include the phrase "internal IP" if the client's IP address is in the
  461. :setting:`INTERNAL_IPS` setting; if not, it will include "EXTERNAL IP".
  462. If the log record contains stack trace information, that stack
  463. trace will be included in the email.
  464. The ``include_html`` argument of ``AdminEmailHandler`` is used to
  465. control whether the traceback email includes an HTML attachment
  466. containing the full content of the debug Web page that would have been
  467. produced if :setting:`DEBUG` were ``True``. To set this value in your
  468. configuration, include it in the handler definition for
  469. ``django.utils.log.AdminEmailHandler``, like this:
  470. .. code-block:: python
  471. 'handlers': {
  472. 'mail_admins': {
  473. 'level': 'ERROR',
  474. 'class': 'django.utils.log.AdminEmailHandler',
  475. 'include_html': True,
  476. }
  477. },
  478. Note that this HTML version of the email contains a full traceback,
  479. with names and values of local variables at each level of the stack, plus
  480. the values of your Django settings. This information is potentially very
  481. sensitive, and you may not want to send it over email. Consider using
  482. something such as `Sentry`_ to get the best of both worlds -- the
  483. rich information of full tracebacks plus the security of *not* sending the
  484. information over email. You may also explicitly designate certain
  485. sensitive information to be filtered out of error reports -- learn more on
  486. :ref:`Filtering error reports<filtering-error-reports>`.
  487. By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
  488. :ref:`email backend <topic-email-backends>` that is being used by the
  489. handler can be overridden, like this:
  490. .. code-block:: python
  491. 'handlers': {
  492. 'mail_admins': {
  493. 'level': 'ERROR',
  494. 'class': 'django.utils.log.AdminEmailHandler',
  495. 'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
  496. }
  497. },
  498. By default, an instance of the email backend specified in
  499. :setting:`EMAIL_BACKEND` will be used.
  500. .. method:: send_mail(subject, message, *args, **kwargs)
  501. Sends emails to admin users. To customize this behavior, you can
  502. subclass the :class:`~django.utils.log.AdminEmailHandler` class and
  503. override this method.
  504. .. _Sentry: https://pypi.org/project/sentry/
  505. Filters
  506. -------
  507. Django provides some log filters in addition to those provided by the Python
  508. logging module.
  509. .. class:: CallbackFilter(callback)
  510. This filter accepts a callback function (which should accept a single
  511. argument, the record to be logged), and calls it for each record that
  512. passes through the filter. Handling of that record will not proceed if the
  513. callback returns False.
  514. For instance, to filter out :exc:`~django.http.UnreadablePostError`
  515. (raised when a user cancels an upload) from the admin emails, you would
  516. create a filter function::
  517. from django.http import UnreadablePostError
  518. def skip_unreadable_post(record):
  519. if record.exc_info:
  520. exc_type, exc_value = record.exc_info[:2]
  521. if isinstance(exc_value, UnreadablePostError):
  522. return False
  523. return True
  524. and then add it to your logging config:
  525. .. code-block:: python
  526. 'filters': {
  527. 'skip_unreadable_posts': {
  528. '()': 'django.utils.log.CallbackFilter',
  529. 'callback': skip_unreadable_post,
  530. }
  531. },
  532. 'handlers': {
  533. 'mail_admins': {
  534. 'level': 'ERROR',
  535. 'filters': ['skip_unreadable_posts'],
  536. 'class': 'django.utils.log.AdminEmailHandler'
  537. }
  538. },
  539. .. class:: RequireDebugFalse()
  540. This filter will only pass on records when settings.DEBUG is False.
  541. This filter is used as follows in the default :setting:`LOGGING`
  542. configuration to ensure that the :class:`AdminEmailHandler` only sends
  543. error emails to admins when :setting:`DEBUG` is ``False``:
  544. .. code-block:: python
  545. 'filters': {
  546. 'require_debug_false': {
  547. '()': 'django.utils.log.RequireDebugFalse',
  548. }
  549. },
  550. 'handlers': {
  551. 'mail_admins': {
  552. 'level': 'ERROR',
  553. 'filters': ['require_debug_false'],
  554. 'class': 'django.utils.log.AdminEmailHandler'
  555. }
  556. },
  557. .. class:: RequireDebugTrue()
  558. This filter is similar to :class:`RequireDebugFalse`, except that records are
  559. passed only when :setting:`DEBUG` is ``True``.
  560. .. _default-logging-configuration:
  561. Django's default logging configuration
  562. ======================================
  563. By default, Django configures the following logging:
  564. When :setting:`DEBUG` is ``True``:
  565. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  566. ``django.server``) at the ``INFO`` level or higher to the console.
  567. When :setting:`DEBUG` is ``False``:
  568. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  569. ``django.server``) with ``ERROR`` or ``CRITICAL`` level to
  570. :class:`AdminEmailHandler`.
  571. Independent of the value of :setting:`DEBUG`:
  572. * The :ref:`django-server-logger` logger sends messages at the ``INFO`` level
  573. or higher to the console.
  574. All loggers except :ref:`django-server-logger` propagate logging to their
  575. parents, up to the root ``django`` logger. The ``console`` and ``mail_admins``
  576. handlers are attached to the root logger to provide the behavior described
  577. above.
  578. See also :ref:`Configuring logging <configuring-logging>` to learn how you can
  579. complement or replace this default logging configuration defined in
  580. :source:`django/utils/log.py`.