logging.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. =======
  2. Logging
  3. =======
  4. .. module:: django.utils.log
  5. :synopsis: Logging tools for Django applications
  6. Overview
  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 a named
  23. 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. .. _logging-how-to:
  88. How to use logging
  89. ==================
  90. Django provides a :ref:`default logging configuration
  91. <default-logging-configuration>`, that for example generates the messages that
  92. appear in the console when using the :djadmin:`runserver`.
  93. Make a basic logging call
  94. -------------------------
  95. Python programmers will often use ``print()`` in their code as a quick and
  96. convenient debugging tool. Using the logging framework is only a little more
  97. effort than that, but it's much more elegant and flexible. As well as being
  98. useful for debugging, logging can also provide you with more - and better
  99. structured - information about the state and health of your application.
  100. To send a log message from within your code, you place a logging call into it.
  101. .. admonition:: Don't be tempted to use logging calls in ``settings.py``
  102. The way that Django logging is configured as part of the ``setup()``
  103. function means that logging calls placed in ``settings.py`` may not work as
  104. expected, because *logging will not be set up at that point*. To explore
  105. logging, use a view function as suggested in the example below.
  106. First, import the Python logging library, and then obtain a logger instance
  107. with :py:func:`logging.getLogger`. The ``getLogger()`` method must be provided
  108. with a name. A good option is to use ``__name__``, which will provide the name
  109. of the current Python module (see :ref:`naming-loggers` for use of explicit
  110. naming)::
  111. import logging
  112. logger = logging.getLogger(__name__)
  113. And then in a function, for example in a view, send a message to the logger::
  114. def some_view(request):
  115. ...
  116. if some_risky_state:
  117. logger.warning('Platform is running at risk')
  118. When this code is executed, that message will be sent to the logger (and if
  119. you're using Django's default logging configuration, it will appear in the
  120. console).
  121. The ``WARNING`` level used in the example above is one of several
  122. :ref:`logging severity levels <topic-logging-parts-loggers>`: ``DEBUG``,
  123. ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. So, another example might be::
  124. logger.critical('Payment system is not responding')
  125. The default logging configuration, which Django inherits from the Python
  126. logging module, prints all messages of level ``WARNING`` and higher to the
  127. console. Django's own defaults will *not* pass ``INFO`` or lower severity
  128. messages from applications other than Django itself to the console - that will
  129. need to be configured explicitly.
  130. .. _naming-loggers:
  131. Naming loggers
  132. --------------
  133. The call to :func:`logging.getLogger()` obtains (creating, if
  134. necessary) an instance of a logger. The logger instance is identified
  135. by a name. This name is used to identify the logger for configuration
  136. purposes.
  137. By convention, the logger name is usually ``__name__``, the name of
  138. the Python module that contains the logger. This allows you to filter
  139. and handle logging calls on a per-module basis. However, if you have
  140. some other way of organizing your logging messages, you can provide
  141. any dot-separated name to identify your logger::
  142. # Get an instance of a specific named logger
  143. logger = logging.getLogger('project.interesting.stuff')
  144. The dotted paths of logger names define a hierarchy. The
  145. ``project.interesting`` logger is considered to be a parent of the
  146. ``project.interesting.stuff`` logger; the ``project`` logger
  147. is a parent of the ``project.interesting`` logger.
  148. Why is the hierarchy important? Well, because loggers can be set to
  149. *propagate* their logging calls to their parents. In this way, you can
  150. define a single set of handlers at the root of a logger tree, and
  151. capture all logging calls in the subtree of loggers. A logger defined
  152. in the ``project`` namespace will catch all logging messages issued on
  153. the ``project.interesting`` and ``project.interesting.stuff`` loggers.
  154. This propagation can be controlled on a per-logger basis. If
  155. you don't want a particular logger to propagate to its parents, you
  156. can turn off this behavior.
  157. Making logging calls
  158. --------------------
  159. The logger instance contains an entry method for each of the default
  160. log levels:
  161. * ``logger.debug()``
  162. * ``logger.info()``
  163. * ``logger.warning()``
  164. * ``logger.error()``
  165. * ``logger.critical()``
  166. There are two other logging calls available:
  167. * ``logger.log()``: Manually emits a logging message with a
  168. specific log level.
  169. * ``logger.exception()``: Creates an ``ERROR`` level logging
  170. message wrapping the current exception stack frame.
  171. .. _configuring-logging:
  172. Configuring logging
  173. ===================
  174. It isn't enough to just put logging calls into your code. You also need to
  175. configure the loggers, handlers, filters, and formatters to ensure you can use
  176. the logging output.
  177. Python's logging library provides several techniques to configure
  178. logging, ranging from a programmatic interface to configuration files.
  179. By default, Django uses the :ref:`dictConfig format
  180. <logging-config-dictschema>`.
  181. In order to configure logging, you use :setting:`LOGGING` to define a
  182. dictionary of logging settings. These settings describes the loggers,
  183. handlers, filters and formatters that you want in your logging setup,
  184. and the log levels and other properties that you want those components
  185. to have.
  186. By default, the :setting:`LOGGING` setting is merged with :ref:`Django's
  187. default logging configuration <default-logging-configuration>` using the
  188. following scheme.
  189. If the ``disable_existing_loggers`` key in the :setting:`LOGGING` dictConfig is
  190. set to ``True`` (which is the ``dictConfig`` default if the key is missing)
  191. then all loggers from the default configuration will be disabled. Disabled
  192. loggers are not the same as removed; the logger will still exist, but will
  193. silently discard anything logged to it, not even propagating entries to a
  194. parent logger. Thus you should be very careful using
  195. ``'disable_existing_loggers': True``; it's probably not what you want. Instead,
  196. you can set ``disable_existing_loggers`` to ``False`` and redefine some or all
  197. of the default loggers; or you can set :setting:`LOGGING_CONFIG` to ``None``
  198. and :ref:`handle logging config yourself <disabling-logging-configuration>`.
  199. Logging is configured as part of the general Django ``setup()`` function.
  200. Therefore, you can be certain that loggers are always ready for use in your
  201. project code.
  202. Examples
  203. --------
  204. The full documentation for :ref:`dictConfig format <logging-config-dictschema>`
  205. is the best source of information about logging configuration dictionaries.
  206. However, to give you a taste of what is possible, here are several examples.
  207. To begin, here's a small configuration that will allow you to output all log
  208. messages to the console:
  209. .. code-block:: python
  210. :caption: settings.py
  211. import os
  212. LOGGING = {
  213. 'version': 1,
  214. 'disable_existing_loggers': False,
  215. 'handlers': {
  216. 'console': {
  217. 'class': 'logging.StreamHandler',
  218. },
  219. },
  220. 'root': {
  221. 'handlers': ['console'],
  222. 'level': 'WARNING',
  223. },
  224. }
  225. This configures the parent ``root`` logger to send messages with the
  226. ``WARNING`` level and higher to the console handler. By adjusting the level to
  227. ``INFO`` or ``DEBUG`` you can display more messages. This may be useful during
  228. development.
  229. Next we can add more fine-grained logging. Here's an example of how to make the
  230. logging system print more messages from just the :ref:`django-logger` named
  231. logger:
  232. .. code-block:: python
  233. :caption: settings.py
  234. import os
  235. LOGGING = {
  236. 'version': 1,
  237. 'disable_existing_loggers': False,
  238. 'handlers': {
  239. 'console': {
  240. 'class': 'logging.StreamHandler',
  241. },
  242. },
  243. 'root': {
  244. 'handlers': ['console'],
  245. 'level': 'WARNING',
  246. },
  247. 'loggers': {
  248. 'django': {
  249. 'handlers': ['console'],
  250. 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
  251. 'propagate': False,
  252. },
  253. },
  254. }
  255. By default, this config sends messages from the ``django`` logger of level
  256. ``INFO`` or higher to the console. This is the same level as Django's default
  257. logging config, except that the default config only displays log records when
  258. ``DEBUG=True``. Django does not log many such ``INFO`` level messages. With
  259. this config, however, you can also set the environment variable
  260. ``DJANGO_LOG_LEVEL=DEBUG`` to see all of Django's debug logging which is very
  261. verbose as it includes all database queries.
  262. You don't have to log to the console. Here's a configuration which writes all
  263. logging from the :ref:`django-logger` named logger to a local file:
  264. .. code-block:: python
  265. :caption: settings.py
  266. LOGGING = {
  267. 'version': 1,
  268. 'disable_existing_loggers': False,
  269. 'handlers': {
  270. 'file': {
  271. 'level': 'DEBUG',
  272. 'class': 'logging.FileHandler',
  273. 'filename': '/path/to/django/debug.log',
  274. },
  275. },
  276. 'loggers': {
  277. 'django': {
  278. 'handlers': ['file'],
  279. 'level': 'DEBUG',
  280. 'propagate': True,
  281. },
  282. },
  283. }
  284. If you use this example, be sure to change the ``'filename'`` path to a
  285. location that's writable by the user that's running the Django application.
  286. Finally, here's an example of a fairly complex logging setup:
  287. .. code-block:: python
  288. :caption: settings.py
  289. LOGGING = {
  290. 'version': 1,
  291. 'disable_existing_loggers': False,
  292. 'formatters': {
  293. 'verbose': {
  294. 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
  295. 'style': '{',
  296. },
  297. 'simple': {
  298. 'format': '{levelname} {message}',
  299. 'style': '{',
  300. },
  301. },
  302. 'filters': {
  303. 'special': {
  304. '()': 'project.logging.SpecialFilter',
  305. 'foo': 'bar',
  306. },
  307. 'require_debug_true': {
  308. '()': 'django.utils.log.RequireDebugTrue',
  309. },
  310. },
  311. 'handlers': {
  312. 'console': {
  313. 'level': 'INFO',
  314. 'filters': ['require_debug_true'],
  315. 'class': 'logging.StreamHandler',
  316. 'formatter': 'simple'
  317. },
  318. 'mail_admins': {
  319. 'level': 'ERROR',
  320. 'class': 'django.utils.log.AdminEmailHandler',
  321. 'filters': ['special']
  322. }
  323. },
  324. 'loggers': {
  325. 'django': {
  326. 'handlers': ['console'],
  327. 'propagate': True,
  328. },
  329. 'django.request': {
  330. 'handlers': ['mail_admins'],
  331. 'level': 'ERROR',
  332. 'propagate': False,
  333. },
  334. 'myproject.custom': {
  335. 'handlers': ['console', 'mail_admins'],
  336. 'level': 'INFO',
  337. 'filters': ['special']
  338. }
  339. }
  340. }
  341. This logging configuration does the following things:
  342. * Identifies the configuration as being in 'dictConfig version 1'
  343. format. At present, this is the only dictConfig format version.
  344. * Defines two formatters:
  345. * ``simple``, that outputs the log level name (e.g., ``DEBUG``) and the log
  346. message.
  347. The ``format`` string is a normal Python formatting string
  348. describing the details that are to be output on each logging
  349. line. The full list of detail that can be output can be
  350. found in :ref:`formatter-objects`.
  351. * ``verbose``, that outputs the log level name, the log
  352. message, plus the time, process, thread and module that
  353. generate the log message.
  354. * Defines two filters:
  355. * ``project.logging.SpecialFilter``, using the alias ``special``. If this
  356. filter required additional arguments, they can be provided as additional
  357. keys in the filter configuration dictionary. In this case, the argument
  358. ``foo`` will be given a value of ``bar`` when instantiating
  359. ``SpecialFilter``.
  360. * ``django.utils.log.RequireDebugTrue``, which passes on records when
  361. :setting:`DEBUG` is ``True``.
  362. * Defines two handlers:
  363. * ``console``, a :class:`~logging.StreamHandler`, which prints any ``INFO``
  364. (or higher) message to ``sys.stderr``. This handler uses the ``simple``
  365. output format.
  366. * ``mail_admins``, an :class:`AdminEmailHandler`, which emails any ``ERROR``
  367. (or higher) message to the site :setting:`ADMINS`. This handler uses the
  368. ``special`` filter.
  369. * Configures three loggers:
  370. * ``django``, which passes all messages to the ``console`` handler.
  371. * ``django.request``, which passes all ``ERROR`` messages to
  372. the ``mail_admins`` handler. In addition, this logger is
  373. marked to *not* propagate messages. This means that log
  374. messages written to ``django.request`` will not be handled
  375. by the ``django`` logger.
  376. * ``myproject.custom``, which passes all messages at ``INFO``
  377. or higher that also pass the ``special`` filter to two
  378. handlers -- the ``console``, and ``mail_admins``. This
  379. means that all ``INFO`` level messages (or higher) will be
  380. printed to the console; ``ERROR`` and ``CRITICAL``
  381. messages will also be output via email.
  382. Custom logging configuration
  383. ----------------------------
  384. If you don't want to use Python's dictConfig format to configure your
  385. logger, you can specify your own configuration scheme.
  386. The :setting:`LOGGING_CONFIG` setting defines the callable that will
  387. be used to configure Django's loggers. By default, it points at
  388. Python's :func:`logging.config.dictConfig()` function. However, if you want to
  389. use a different configuration process, you can use any other callable
  390. that takes a single argument. The contents of :setting:`LOGGING` will
  391. be provided as the value of that argument when logging is configured.
  392. .. _disabling-logging-configuration:
  393. Disabling logging configuration
  394. -------------------------------
  395. If you don't want to configure logging at all (or you want to manually
  396. configure logging using your own approach), you can set
  397. :setting:`LOGGING_CONFIG` to ``None``. This will disable the
  398. configuration process for :ref:`Django's default logging
  399. <default-logging-configuration>`.
  400. Setting :setting:`LOGGING_CONFIG` to ``None`` only means that the automatic
  401. configuration process is disabled, not logging itself. If you disable the
  402. configuration process, Django will still make logging calls, falling back to
  403. whatever default logging behavior is defined.
  404. Here's an example that disables Django's logging configuration and then
  405. manually configures logging:
  406. .. code-block:: python
  407. :caption: settings.py
  408. LOGGING_CONFIG = None
  409. import logging.config
  410. logging.config.dictConfig(...)
  411. Note that the default configuration process only calls
  412. :setting:`LOGGING_CONFIG` once settings are fully-loaded. In contrast, manually
  413. configuring the logging in your settings file will load your logging config
  414. immediately. As such, your logging config must appear *after* any settings on
  415. which it depends.
  416. Django logging extension reference
  417. ==================================
  418. Django provides a number of utilities to handle the unique
  419. requirements of logging in a web server environment.
  420. Loggers
  421. -------
  422. Django provides several built-in loggers.
  423. .. _django-logger:
  424. ``django``
  425. ~~~~~~~~~~
  426. The catch-all logger for messages in the ``django`` hierarchy. No messages are
  427. posted using this name but instead using one of the loggers below.
  428. .. _django-request-logger:
  429. ``django.request``
  430. ~~~~~~~~~~~~~~~~~~
  431. Log messages related to the handling of requests. 5XX responses are
  432. raised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``
  433. messages. Requests that are logged to the ``django.security`` logger aren't
  434. logged to ``django.request``.
  435. Messages to this logger have the following extra context:
  436. * ``status_code``: The HTTP response code associated with the
  437. request.
  438. * ``request``: The request object that generated the logging
  439. message.
  440. .. _django-server-logger:
  441. ``django.server``
  442. ~~~~~~~~~~~~~~~~~
  443. Log messages related to the handling of requests received by the server invoked
  444. by the :djadmin:`runserver` command. HTTP 5XX responses are logged as ``ERROR``
  445. messages, 4XX responses are logged as ``WARNING`` messages, and everything else
  446. is logged as ``INFO``.
  447. Messages to this logger have the following extra context:
  448. * ``status_code``: The HTTP response code associated with the request.
  449. * ``request``: The request object that generated the logging message.
  450. .. _django-template-logger:
  451. ``django.template``
  452. ~~~~~~~~~~~~~~~~~~~
  453. Log messages related to the rendering of templates.
  454. * Missing context variables are logged as ``DEBUG`` messages.
  455. .. _django-db-logger:
  456. ``django.db.backends``
  457. ~~~~~~~~~~~~~~~~~~~~~~
  458. Messages relating to the interaction of code with the database. For example,
  459. every application-level SQL statement executed by a request is logged at the
  460. ``DEBUG`` level to this logger.
  461. Messages to this logger have the following extra context:
  462. * ``duration``: The time taken to execute the SQL statement.
  463. * ``sql``: The SQL statement that was executed.
  464. * ``params``: The parameters that were used in the SQL call.
  465. For performance reasons, SQL logging is only enabled when
  466. ``settings.DEBUG`` is set to ``True``, regardless of the logging
  467. level or handlers that are installed.
  468. This logging does not include framework-level initialization (e.g.
  469. ``SET TIMEZONE``) or transaction management queries (e.g. ``BEGIN``,
  470. ``COMMIT``, and ``ROLLBACK``). Turn on query logging in your database if you
  471. wish to view all database queries.
  472. .. _django-security-logger:
  473. ``django.security.*``
  474. ~~~~~~~~~~~~~~~~~~~~~~
  475. The security loggers will receive messages on any occurrence of
  476. :exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
  477. errors. There is a sub-logger for each subtype of security error, including all
  478. ``SuspiciousOperation``\s. The level of the log event depends on where the
  479. exception is handled. Most occurrences are logged as a warning, while
  480. any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
  481. error. For example, when an HTTP ``Host`` header is included in a request from
  482. a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
  483. response, and an error message will be logged to the
  484. ``django.security.DisallowedHost`` logger.
  485. These log events will reach the ``django`` logger by default, which mails error
  486. events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
  487. to a ``SuspiciousOperation`` will not be logged to the ``django.request``
  488. logger, but only to the ``django.security`` logger.
  489. To silence a particular type of ``SuspiciousOperation``, you can override that
  490. specific logger following this example::
  491. 'handlers': {
  492. 'null': {
  493. 'class': 'logging.NullHandler',
  494. },
  495. },
  496. 'loggers': {
  497. 'django.security.DisallowedHost': {
  498. 'handlers': ['null'],
  499. 'propagate': False,
  500. },
  501. },
  502. Other ``django.security`` loggers not based on ``SuspiciousOperation`` are:
  503. * ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.
  504. ``django.db.backends.schema``
  505. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  506. Logs the SQL queries that are executed during schema changes to the database by
  507. the :doc:`migrations framework </topics/migrations>`. Note that it won't log the
  508. queries executed by :class:`~django.db.migrations.operations.RunPython`.
  509. Messages to this logger have ``params`` and ``sql`` in their extra context (but
  510. unlike ``django.db.backends``, not duration). The values have the same meaning
  511. as explained in :ref:`django-db-logger`.
  512. Handlers
  513. --------
  514. Django provides one log handler in addition to those provided by the
  515. Python logging module.
  516. .. class:: AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)
  517. This handler sends an email to the site :setting:`ADMINS` for each log
  518. message it receives.
  519. If the log record contains a ``request`` attribute, the full details
  520. of the request will be included in the email. The email subject will
  521. include the phrase "internal IP" if the client's IP address is in the
  522. :setting:`INTERNAL_IPS` setting; if not, it will include "EXTERNAL IP".
  523. If the log record contains stack trace information, that stack
  524. trace will be included in the email.
  525. The ``include_html`` argument of ``AdminEmailHandler`` is used to
  526. control whether the traceback email includes an HTML attachment
  527. containing the full content of the debug Web page that would have been
  528. produced if :setting:`DEBUG` were ``True``. To set this value in your
  529. configuration, include it in the handler definition for
  530. ``django.utils.log.AdminEmailHandler``, like this::
  531. 'handlers': {
  532. 'mail_admins': {
  533. 'level': 'ERROR',
  534. 'class': 'django.utils.log.AdminEmailHandler',
  535. 'include_html': True,
  536. }
  537. },
  538. Be aware of the :ref:`security implications of logging
  539. <logging-security-implications>` when using the ``AdminEmailHandler``.
  540. By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
  541. :ref:`email backend <topic-email-backends>` that is being used by the
  542. handler can be overridden, like this::
  543. 'handlers': {
  544. 'mail_admins': {
  545. 'level': 'ERROR',
  546. 'class': 'django.utils.log.AdminEmailHandler',
  547. 'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
  548. }
  549. },
  550. By default, an instance of the email backend specified in
  551. :setting:`EMAIL_BACKEND` will be used.
  552. The ``reporter_class`` argument of ``AdminEmailHandler`` allows providing
  553. an ``django.views.debug.ExceptionReporter`` subclass to customize the
  554. traceback text sent in the email body. You provide a string import path to
  555. the class you wish to use, like this::
  556. 'handlers': {
  557. 'mail_admins': {
  558. 'level': 'ERROR',
  559. 'class': 'django.utils.log.AdminEmailHandler',
  560. 'include_html': True,
  561. 'reporter_class': 'somepackage.error_reporter.CustomErrorReporter'
  562. }
  563. },
  564. .. method:: send_mail(subject, message, *args, **kwargs)
  565. Sends emails to admin users. To customize this behavior, you can
  566. subclass the :class:`~django.utils.log.AdminEmailHandler` class and
  567. override this method.
  568. Filters
  569. -------
  570. Django provides some log filters in addition to those provided by the Python
  571. logging module.
  572. .. class:: CallbackFilter(callback)
  573. This filter accepts a callback function (which should accept a single
  574. argument, the record to be logged), and calls it for each record that
  575. passes through the filter. Handling of that record will not proceed if the
  576. callback returns False.
  577. For instance, to filter out :exc:`~django.http.UnreadablePostError`
  578. (raised when a user cancels an upload) from the admin emails, you would
  579. create a filter function::
  580. from django.http import UnreadablePostError
  581. def skip_unreadable_post(record):
  582. if record.exc_info:
  583. exc_type, exc_value = record.exc_info[:2]
  584. if isinstance(exc_value, UnreadablePostError):
  585. return False
  586. return True
  587. and then add it to your logging config::
  588. 'filters': {
  589. 'skip_unreadable_posts': {
  590. '()': 'django.utils.log.CallbackFilter',
  591. 'callback': skip_unreadable_post,
  592. }
  593. },
  594. 'handlers': {
  595. 'mail_admins': {
  596. 'level': 'ERROR',
  597. 'filters': ['skip_unreadable_posts'],
  598. 'class': 'django.utils.log.AdminEmailHandler'
  599. }
  600. },
  601. .. class:: RequireDebugFalse()
  602. This filter will only pass on records when settings.DEBUG is False.
  603. This filter is used as follows in the default :setting:`LOGGING`
  604. configuration to ensure that the :class:`AdminEmailHandler` only sends
  605. error emails to admins when :setting:`DEBUG` is ``False``::
  606. 'filters': {
  607. 'require_debug_false': {
  608. '()': 'django.utils.log.RequireDebugFalse',
  609. }
  610. },
  611. 'handlers': {
  612. 'mail_admins': {
  613. 'level': 'ERROR',
  614. 'filters': ['require_debug_false'],
  615. 'class': 'django.utils.log.AdminEmailHandler'
  616. }
  617. },
  618. .. class:: RequireDebugTrue()
  619. This filter is similar to :class:`RequireDebugFalse`, except that records are
  620. passed only when :setting:`DEBUG` is ``True``.
  621. .. _default-logging-configuration:
  622. Django's default logging configuration
  623. ======================================
  624. By default, Django configures the following logging:
  625. When :setting:`DEBUG` is ``True``:
  626. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  627. ``django.server``) at the ``INFO`` level or higher to the console.
  628. When :setting:`DEBUG` is ``False``:
  629. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  630. ``django.server``) with ``ERROR`` or ``CRITICAL`` level to
  631. :class:`AdminEmailHandler`.
  632. Independent of the value of :setting:`DEBUG`:
  633. * The :ref:`django-server-logger` logger sends messages at the ``INFO`` level
  634. or higher to the console.
  635. All loggers except :ref:`django-server-logger` propagate logging to their
  636. parents, up to the root ``django`` logger. The ``console`` and ``mail_admins``
  637. handlers are attached to the root logger to provide the behavior described
  638. above.
  639. See also :ref:`Configuring logging <configuring-logging>` to learn how you can
  640. complement or replace this default logging configuration defined in
  641. :source:`django/utils/log.py`.
  642. .. _logging-security-implications:
  643. Security implications
  644. =====================
  645. The logging system handles potentially sensitive information. For example, the
  646. log record may contain information about a web request or a stack trace, while
  647. some of the data you collect in your own loggers may also have security
  648. implications. You need to be sure you know:
  649. * what information is collected
  650. * where it will subsequently be stored
  651. * how it will be transferred
  652. * who might have access to it.
  653. To help control the collection of sensitive information, you can explicitly
  654. designate certain sensitive information to be filtered out of error reports --
  655. read more about how to :ref:`filter error reports <filtering-error-reports>`.
  656. ``AdminEmailHandler``
  657. ---------------------
  658. The built-in :class:`AdminEmailHandler` deserves a mention in the context of
  659. security. If its ``include_html`` option is enabled, the email message it sends
  660. will contain a full traceback, with names and values of local variables at each
  661. level of the stack, plus the values of your Django settings (in other words,
  662. the same level of detail that is exposed in a web page when :setting:`DEBUG` is
  663. ``True``).
  664. It's generally not considered a good idea to send such potentially sensitive
  665. information over email. Consider instead using one of the many third-party
  666. services to which detailed logs can be sent to get the best of multiple worlds
  667. -- the rich information of full tracebacks, clear management of who is notified
  668. and has access to the information, and so on.