logging.txt 13 KB

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