logging.txt 15 KB

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