logging.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. .. _logging-ref:
  2. =======
  3. Logging
  4. =======
  5. .. seealso::
  6. * :ref:`logging-how-to`
  7. * :ref:`Django logging overview <logging-explanation>`
  8. .. module:: django.utils.log
  9. :synopsis: Logging tools for Django applications
  10. Django's logging module extends Python's builtin :mod:`logging`.
  11. Logging is configured as part of the general Django :func:`django.setup`
  12. function, so it's always available unless explicitly disabled.
  13. .. _default-logging-configuration:
  14. Django's default logging configuration
  15. ======================================
  16. By default, Django uses Python's :ref:`logging.config.dictConfig format
  17. <logging-config-dictschema>`.
  18. Default logging conditions
  19. --------------------------
  20. The full set of default logging conditions are:
  21. When :setting:`DEBUG` is ``True``:
  22. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  23. ``django.server``) at the ``INFO`` level or higher to the console.
  24. When :setting:`DEBUG` is ``False``:
  25. * The ``django`` logger sends messages in the ``django`` hierarchy (except
  26. ``django.server``) with ``ERROR`` or ``CRITICAL`` level to
  27. :class:`AdminEmailHandler`.
  28. Independently of the value of :setting:`DEBUG`:
  29. * The :ref:`django-server-logger` logger sends messages at the ``INFO`` level
  30. or higher to the console.
  31. All loggers except :ref:`django-server-logger` propagate logging to their
  32. parents, up to the root ``django`` logger. The ``console`` and ``mail_admins``
  33. handlers are attached to the root logger to provide the behavior described
  34. above.
  35. Python's own defaults send records of level ``WARNING`` and higher
  36. to the console.
  37. .. _default-logging-definition:
  38. Default logging definition
  39. --------------------------
  40. Django's default logging configuration inherits Python's defaults. It's
  41. available as ``django.utils.log.DEFAULT_LOGGING`` and defined in
  42. :source:`django/utils/log.py`::
  43. {
  44. 'version': 1,
  45. 'disable_existing_loggers': False,
  46. 'filters': {
  47. 'require_debug_false': {
  48. '()': 'django.utils.log.RequireDebugFalse',
  49. },
  50. 'require_debug_true': {
  51. '()': 'django.utils.log.RequireDebugTrue',
  52. },
  53. },
  54. 'formatters': {
  55. 'django.server': {
  56. '()': 'django.utils.log.ServerFormatter',
  57. 'format': '[{server_time}] {message}',
  58. 'style': '{',
  59. }
  60. },
  61. 'handlers': {
  62. 'console': {
  63. 'level': 'INFO',
  64. 'filters': ['require_debug_true'],
  65. 'class': 'logging.StreamHandler',
  66. },
  67. 'django.server': {
  68. 'level': 'INFO',
  69. 'class': 'logging.StreamHandler',
  70. 'formatter': 'django.server',
  71. },
  72. 'mail_admins': {
  73. 'level': 'ERROR',
  74. 'filters': ['require_debug_false'],
  75. 'class': 'django.utils.log.AdminEmailHandler'
  76. }
  77. },
  78. 'loggers': {
  79. 'django': {
  80. 'handlers': ['console', 'mail_admins'],
  81. 'level': 'INFO',
  82. },
  83. 'django.server': {
  84. 'handlers': ['django.server'],
  85. 'level': 'INFO',
  86. 'propagate': False,
  87. },
  88. }
  89. }
  90. See :ref:`configuring-logging` on how to complement or replace this default
  91. logging configuration.
  92. Django logging extensions
  93. =========================
  94. Django provides a number of utilities to handle the particular requirements of
  95. logging in a web server environment.
  96. Loggers
  97. -------
  98. Django provides several built-in loggers.
  99. .. _django-logger:
  100. ``django``
  101. ~~~~~~~~~~
  102. The parent logger for messages in the ``django`` :ref:`named logger hierarchy
  103. <naming-loggers-hierarchy>`. Django does not post messages using this name.
  104. Instead, it uses one of the loggers below.
  105. .. _django-request-logger:
  106. ``django.request``
  107. ~~~~~~~~~~~~~~~~~~
  108. Log messages related to the handling of requests. 5XX responses are
  109. raised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``
  110. messages. Requests that are logged to the ``django.security`` logger aren't
  111. logged to ``django.request``.
  112. Messages to this logger have the following extra context:
  113. * ``status_code``: The HTTP response code associated with the request.
  114. * ``request``: The request object that generated the logging message.
  115. .. _django-server-logger:
  116. ``django.server``
  117. ~~~~~~~~~~~~~~~~~
  118. Log messages related to the handling of requests received by the server invoked
  119. by the :djadmin:`runserver` command. HTTP 5XX responses are logged as ``ERROR``
  120. messages, 4XX responses are logged as ``WARNING`` messages, and everything else
  121. is logged as ``INFO``.
  122. Messages to this logger have the following extra context:
  123. * ``status_code``: The HTTP response code associated with the request.
  124. * ``request``: The request object that generated the logging message.
  125. .. _django-template-logger:
  126. ``django.template``
  127. ~~~~~~~~~~~~~~~~~~~
  128. Log messages related to the rendering of templates.
  129. * Missing context variables are logged as ``DEBUG`` messages.
  130. .. _django-db-logger:
  131. ``django.db.backends``
  132. ~~~~~~~~~~~~~~~~~~~~~~
  133. Messages relating to the interaction of code with the database. For example,
  134. every application-level SQL statement executed by a request is logged at the
  135. ``DEBUG`` level to this logger.
  136. Messages to this logger have the following extra context:
  137. * ``duration``: The time taken to execute the SQL statement.
  138. * ``sql``: The SQL statement that was executed.
  139. * ``params``: The parameters that were used in the SQL call.
  140. * ``alias``: The alias of the database used in the SQL call.
  141. For performance reasons, SQL logging is only enabled when
  142. ``settings.DEBUG`` is set to ``True``, regardless of the logging
  143. level or handlers that are installed.
  144. This logging does not include framework-level initialization (e.g.
  145. ``SET TIMEZONE``). Turn on query logging in your database if you wish to view
  146. all database queries.
  147. .. versionchanged:: 4.2
  148. Support for logging transaction management queries (``BEGIN``, ``COMMIT``,
  149. and ``ROLLBACK``) was added.
  150. .. _django-security-logger:
  151. ``django.security.*``
  152. ~~~~~~~~~~~~~~~~~~~~~
  153. The security loggers will receive messages on any occurrence of
  154. :exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
  155. errors. There is a sub-logger for each subtype of security error, including all
  156. ``SuspiciousOperation``\s. The level of the log event depends on where the
  157. exception is handled. Most occurrences are logged as a warning, while
  158. any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
  159. error. For example, when an HTTP ``Host`` header is included in a request from
  160. a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
  161. response, and an error message will be logged to the
  162. ``django.security.DisallowedHost`` logger.
  163. These log events will reach the ``django`` logger by default, which mails error
  164. events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
  165. to a ``SuspiciousOperation`` will not be logged to the ``django.request``
  166. logger, but only to the ``django.security`` logger.
  167. To silence a particular type of ``SuspiciousOperation``, you can override that
  168. specific logger following this example::
  169. LOGGING = {
  170. # ...
  171. 'handlers': {
  172. 'null': {
  173. 'class': 'logging.NullHandler',
  174. },
  175. },
  176. 'loggers': {
  177. 'django.security.DisallowedHost': {
  178. 'handlers': ['null'],
  179. 'propagate': False,
  180. },
  181. },
  182. # ...
  183. }
  184. Other ``django.security`` loggers not based on ``SuspiciousOperation`` are:
  185. * ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.
  186. ``django.db.backends.schema``
  187. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  188. Logs the SQL queries that are executed during schema changes to the database by
  189. the :doc:`migrations framework </topics/migrations>`. Note that it won't log the
  190. queries executed by :class:`~django.db.migrations.operations.RunPython`.
  191. Messages to this logger have ``params`` and ``sql`` in their extra context (but
  192. unlike ``django.db.backends``, not duration). The values have the same meaning
  193. as explained in :ref:`django-db-logger`.
  194. Handlers
  195. --------
  196. Django provides one log handler in addition to :mod:`those provided by the
  197. Python logging module <python:logging.handlers>`.
  198. .. class:: AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)
  199. This handler sends an email to the site :setting:`ADMINS` for each log
  200. message it receives.
  201. If the log record contains a ``request`` attribute, the full details
  202. of the request will be included in the email. The email subject will
  203. include the phrase "internal IP" if the client's IP address is in the
  204. :setting:`INTERNAL_IPS` setting; if not, it will include "EXTERNAL IP".
  205. If the log record contains stack trace information, that stack
  206. trace will be included in the email.
  207. The ``include_html`` argument of ``AdminEmailHandler`` is used to
  208. control whether the traceback email includes an HTML attachment
  209. containing the full content of the debug web page that would have been
  210. produced if :setting:`DEBUG` were ``True``. To set this value in your
  211. configuration, include it in the handler definition for
  212. ``django.utils.log.AdminEmailHandler``, like this::
  213. 'handlers': {
  214. 'mail_admins': {
  215. 'level': 'ERROR',
  216. 'class': 'django.utils.log.AdminEmailHandler',
  217. 'include_html': True,
  218. },
  219. }
  220. Be aware of the :ref:`security implications of logging
  221. <logging-security-implications>` when using the ``AdminEmailHandler``.
  222. By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
  223. :ref:`email backend <topic-email-backends>` that is being used by the
  224. handler can be overridden, like this::
  225. 'handlers': {
  226. 'mail_admins': {
  227. 'level': 'ERROR',
  228. 'class': 'django.utils.log.AdminEmailHandler',
  229. 'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
  230. },
  231. }
  232. By default, an instance of the email backend specified in
  233. :setting:`EMAIL_BACKEND` will be used.
  234. The ``reporter_class`` argument of ``AdminEmailHandler`` allows providing
  235. an ``django.views.debug.ExceptionReporter`` subclass to customize the
  236. traceback text sent in the email body. You provide a string import path to
  237. the class you wish to use, like this::
  238. 'handlers': {
  239. 'mail_admins': {
  240. 'level': 'ERROR',
  241. 'class': 'django.utils.log.AdminEmailHandler',
  242. 'include_html': True,
  243. 'reporter_class': 'somepackage.error_reporter.CustomErrorReporter',
  244. },
  245. }
  246. .. method:: send_mail(subject, message, *args, **kwargs)
  247. Sends emails to admin users. To customize this behavior, you can
  248. subclass the :class:`~django.utils.log.AdminEmailHandler` class and
  249. override this method.
  250. Filters
  251. -------
  252. Django provides some log filters in addition to those provided by the Python
  253. logging module.
  254. .. class:: CallbackFilter(callback)
  255. This filter accepts a callback function (which should accept a single
  256. argument, the record to be logged), and calls it for each record that
  257. passes through the filter. Handling of that record will not proceed if the
  258. callback returns False.
  259. For instance, to filter out :exc:`~django.http.UnreadablePostError`
  260. (raised when a user cancels an upload) from the admin emails, you would
  261. create a filter function::
  262. from django.http import UnreadablePostError
  263. def skip_unreadable_post(record):
  264. if record.exc_info:
  265. exc_type, exc_value = record.exc_info[:2]
  266. if isinstance(exc_value, UnreadablePostError):
  267. return False
  268. return True
  269. and then add it to your logging config::
  270. LOGGING = {
  271. # ...
  272. 'filters': {
  273. 'skip_unreadable_posts': {
  274. '()': 'django.utils.log.CallbackFilter',
  275. 'callback': skip_unreadable_post,
  276. },
  277. },
  278. 'handlers': {
  279. 'mail_admins': {
  280. 'level': 'ERROR',
  281. 'filters': ['skip_unreadable_posts'],
  282. 'class': 'django.utils.log.AdminEmailHandler',
  283. },
  284. },
  285. # ...
  286. }
  287. .. class:: RequireDebugFalse()
  288. This filter will only pass on records when settings.DEBUG is False.
  289. This filter is used as follows in the default :setting:`LOGGING`
  290. configuration to ensure that the :class:`AdminEmailHandler` only sends
  291. error emails to admins when :setting:`DEBUG` is ``False``::
  292. LOGGING = {
  293. # ...
  294. 'filters': {
  295. 'require_debug_false': {
  296. '()': 'django.utils.log.RequireDebugFalse',
  297. },
  298. },
  299. 'handlers': {
  300. 'mail_admins': {
  301. 'level': 'ERROR',
  302. 'filters': ['require_debug_false'],
  303. 'class': 'django.utils.log.AdminEmailHandler',
  304. },
  305. },
  306. # ...
  307. }
  308. .. class:: RequireDebugTrue()
  309. This filter is similar to :class:`RequireDebugFalse`, except that records are
  310. passed only when :setting:`DEBUG` is ``True``.