logging.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 (a :py:class:`socket.socket`) 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-utils-autoreloader-logger:
  151. ``django.utils.autoreload``
  152. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  153. Log messages related to automatic code reloading during the execution of the
  154. Django development server. This logger generates an ``INFO`` message upon
  155. detecting a modification in a source code file and may produce ``WARNING``
  156. messages during filesystem inspection and event subscription processes.
  157. .. _django-contrib-gis-logger:
  158. ``django.contrib.gis``
  159. ~~~~~~~~~~~~~~~~~~~~~~
  160. Log messages related to :doc:`contrib/gis/index` at various points: during the
  161. loading of external GeoSpatial libraries (GEOS, GDAL, etc.) and when reporting
  162. errors. Each ``ERROR`` log record includes the caught exception and relevant
  163. contextual data.
  164. .. _django-dispatch-logger:
  165. ``django.dispatch``
  166. ~~~~~~~~~~~~~~~~~~~
  167. This logger is used in :doc:`signals`, specifically within the
  168. :mod:`~django.dispatch.Signal` class, to report issues when dispatching a
  169. signal to a connected receiver. The ``ERROR`` log record includes the caught
  170. exception as ``exc_info`` and adds the following extra context:
  171. * ``receiver``: The name of the receiver.
  172. * ``err``: The exception that occurred when calling the receiver.
  173. .. _django-security-logger:
  174. ``django.security.*``
  175. ~~~~~~~~~~~~~~~~~~~~~
  176. The security loggers will receive messages on any occurrence of
  177. :exc:`~django.core.exceptions.SuspiciousOperation` and other security-related
  178. errors. There is a sub-logger for each subtype of security error, including all
  179. ``SuspiciousOperation``\s. The level of the log event depends on where the
  180. exception is handled. Most occurrences are logged as a warning, while
  181. any ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an
  182. error. For example, when an HTTP ``Host`` header is included in a request from
  183. a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
  184. response, and an error message will be logged to the
  185. ``django.security.DisallowedHost`` logger.
  186. These log events will reach the ``django`` logger by default, which mails error
  187. events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
  188. to a ``SuspiciousOperation`` will not be logged to the ``django.request``
  189. logger, but only to the ``django.security`` logger.
  190. To silence a particular type of ``SuspiciousOperation``, you can override that
  191. specific logger following this example::
  192. LOGGING = {
  193. # ...
  194. "handlers": {
  195. "null": {
  196. "class": "logging.NullHandler",
  197. },
  198. },
  199. "loggers": {
  200. "django.security.DisallowedHost": {
  201. "handlers": ["null"],
  202. "propagate": False,
  203. },
  204. },
  205. # ...
  206. }
  207. Other ``django.security`` loggers not based on ``SuspiciousOperation`` are:
  208. * ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.
  209. ``django.db.backends.schema``
  210. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  211. Logs the SQL queries that are executed during schema changes to the database by
  212. the :doc:`migrations framework </topics/migrations>`. Note that it won't log the
  213. queries executed by :class:`~django.db.migrations.operations.RunPython`.
  214. Messages to this logger have ``params`` and ``sql`` in their extra context (but
  215. unlike ``django.db.backends``, not duration). The values have the same meaning
  216. as explained in :ref:`django-db-logger`.
  217. Handlers
  218. --------
  219. Django provides one log handler in addition to :mod:`those provided by the
  220. Python logging module <python:logging.handlers>`.
  221. .. class:: AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)
  222. This handler sends an email to the site :setting:`ADMINS` for each log
  223. message it receives.
  224. If the log record contains a ``request`` attribute, the full details
  225. of the request will be included in the email. The email subject will
  226. include the phrase "internal IP" if the client's IP address is in the
  227. :setting:`INTERNAL_IPS` setting; if not, it will include "EXTERNAL IP".
  228. If the log record contains stack trace information, that stack
  229. trace will be included in the email.
  230. The ``include_html`` argument of ``AdminEmailHandler`` is used to
  231. control whether the traceback email includes an HTML attachment
  232. containing the full content of the debug web page that would have been
  233. produced if :setting:`DEBUG` were ``True``. To set this value in your
  234. configuration, include it in the handler definition for
  235. ``django.utils.log.AdminEmailHandler``, like this::
  236. "handlers": {
  237. "mail_admins": {
  238. "level": "ERROR",
  239. "class": "django.utils.log.AdminEmailHandler",
  240. "include_html": True,
  241. },
  242. }
  243. Be aware of the :ref:`security implications of logging
  244. <logging-security-implications>` when using the ``AdminEmailHandler``.
  245. By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
  246. :ref:`email backend <topic-email-backends>` that is being used by the
  247. handler can be overridden, like this::
  248. "handlers": {
  249. "mail_admins": {
  250. "level": "ERROR",
  251. "class": "django.utils.log.AdminEmailHandler",
  252. "email_backend": "django.core.mail.backends.filebased.EmailBackend",
  253. },
  254. }
  255. By default, an instance of the email backend specified in
  256. :setting:`EMAIL_BACKEND` will be used.
  257. The ``reporter_class`` argument of ``AdminEmailHandler`` allows providing
  258. an ``django.views.debug.ExceptionReporter`` subclass to customize the
  259. traceback text sent in the email body. You provide a string import path to
  260. the class you wish to use, like this::
  261. "handlers": {
  262. "mail_admins": {
  263. "level": "ERROR",
  264. "class": "django.utils.log.AdminEmailHandler",
  265. "include_html": True,
  266. "reporter_class": "somepackage.error_reporter.CustomErrorReporter",
  267. },
  268. }
  269. .. method:: send_mail(subject, message, *args, **kwargs)
  270. Sends emails to admin users. To customize this behavior, you can
  271. subclass the :class:`~django.utils.log.AdminEmailHandler` class and
  272. override this method.
  273. Filters
  274. -------
  275. Django provides some log filters in addition to those provided by the Python
  276. logging module.
  277. .. class:: CallbackFilter(callback)
  278. This filter accepts a callback function (which should accept a single
  279. argument, the record to be logged), and calls it for each record that
  280. passes through the filter. Handling of that record will not proceed if the
  281. callback returns False.
  282. For instance, to filter out :exc:`~django.http.UnreadablePostError`
  283. (raised when a user cancels an upload) from the admin emails, you would
  284. create a filter function::
  285. from django.http import UnreadablePostError
  286. def skip_unreadable_post(record):
  287. if record.exc_info:
  288. exc_type, exc_value = record.exc_info[:2]
  289. if isinstance(exc_value, UnreadablePostError):
  290. return False
  291. return True
  292. and then add it to your logging config::
  293. LOGGING = {
  294. # ...
  295. "filters": {
  296. "skip_unreadable_posts": {
  297. "()": "django.utils.log.CallbackFilter",
  298. "callback": skip_unreadable_post,
  299. },
  300. },
  301. "handlers": {
  302. "mail_admins": {
  303. "level": "ERROR",
  304. "filters": ["skip_unreadable_posts"],
  305. "class": "django.utils.log.AdminEmailHandler",
  306. },
  307. },
  308. # ...
  309. }
  310. .. class:: RequireDebugFalse()
  311. This filter will only pass on records when settings.DEBUG is False.
  312. This filter is used as follows in the default :setting:`LOGGING`
  313. configuration to ensure that the :class:`AdminEmailHandler` only sends
  314. error emails to admins when :setting:`DEBUG` is ``False``::
  315. LOGGING = {
  316. # ...
  317. "filters": {
  318. "require_debug_false": {
  319. "()": "django.utils.log.RequireDebugFalse",
  320. },
  321. },
  322. "handlers": {
  323. "mail_admins": {
  324. "level": "ERROR",
  325. "filters": ["require_debug_false"],
  326. "class": "django.utils.log.AdminEmailHandler",
  327. },
  328. },
  329. # ...
  330. }
  331. .. class:: RequireDebugTrue()
  332. This filter is similar to :class:`RequireDebugFalse`, except that records are
  333. passed only when :setting:`DEBUG` is ``True``.