logging.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. .. _logging-explanation:
  2. =======
  3. Logging
  4. =======
  5. .. seealso::
  6. * :ref:`logging-how-to`
  7. * :ref:`Django logging reference <logging-ref>`
  8. Python programmers will often use ``print()`` in their code as a quick and
  9. convenient debugging tool. Using the logging framework is only a little more
  10. effort than that, but it's much more elegant and flexible. As well as being
  11. useful for debugging, logging can also provide you with more - and better
  12. structured - information about the state and health of your application.
  13. Overview
  14. ========
  15. Django uses and extends Python's builtin :mod:`logging` module to perform
  16. system logging. This module is discussed in detail in Python's own
  17. documentation; this section provides a quick overview.
  18. The cast of players
  19. -------------------
  20. A Python logging configuration consists of four parts:
  21. * :ref:`topic-logging-parts-loggers`
  22. * :ref:`topic-logging-parts-handlers`
  23. * :ref:`topic-logging-parts-filters`
  24. * :ref:`topic-logging-parts-formatters`
  25. .. _topic-logging-parts-loggers:
  26. Loggers
  27. ~~~~~~~
  28. A *logger* is the entry point into the logging system. Each logger is a named
  29. bucket to which messages can be written for processing.
  30. A logger is configured to have a *log level*. This log level describes
  31. the severity of the messages that the logger will handle. Python
  32. defines the following log levels:
  33. * ``DEBUG``: Low level system information for debugging purposes
  34. * ``INFO``: General system information
  35. * ``WARNING``: Information describing a minor problem that has
  36. occurred.
  37. * ``ERROR``: Information describing a major problem that has
  38. occurred.
  39. * ``CRITICAL``: Information describing a critical problem that has
  40. occurred.
  41. Each message that is written to the logger is a *Log Record*. Each log
  42. record also has a *log level* indicating the severity of that specific
  43. message. A log record can also contain useful metadata that describes
  44. the event that is being logged. This can include details such as a
  45. stack trace or an error code.
  46. When a message is given to the logger, the log level of the message is
  47. compared to the log level of the logger. If the log level of the
  48. message meets or exceeds the log level of the logger itself, the
  49. message will undergo further processing. If it doesn't, the message
  50. will be ignored.
  51. Once a logger has determined that a message needs to be processed,
  52. it is passed to a *Handler*.
  53. .. _topic-logging-parts-handlers:
  54. Handlers
  55. ~~~~~~~~
  56. The *handler* is the engine that determines what happens to each message
  57. in a logger. It describes a particular logging behavior, such as
  58. writing a message to the screen, to a file, or to a network socket.
  59. Like loggers, handlers also have a log level. If the log level of a
  60. log record doesn't meet or exceed the level of the handler, the
  61. handler will ignore the message.
  62. A logger can have multiple handlers, and each handler can have a
  63. different log level. In this way, it is possible to provide different
  64. forms of notification depending on the importance of a message. For
  65. example, you could install one handler that forwards ``ERROR`` and
  66. ``CRITICAL`` messages to a paging service, while a second handler
  67. logs all messages (including ``ERROR`` and ``CRITICAL`` messages) to a
  68. file for later analysis.
  69. .. _topic-logging-parts-filters:
  70. Filters
  71. ~~~~~~~
  72. A *filter* is used to provide additional control over which log records
  73. are passed from logger to handler.
  74. By default, any log message that meets log level requirements will be
  75. handled. However, by installing a filter, you can place additional
  76. criteria on the logging process. For example, you could install a
  77. filter that only allows ``ERROR`` messages from a particular source to
  78. be emitted.
  79. Filters can also be used to modify the logging record prior to being
  80. emitted. For example, you could write a filter that downgrades
  81. ``ERROR`` log records to ``WARNING`` records if a particular set of
  82. criteria are met.
  83. Filters can be installed on loggers or on handlers; multiple filters
  84. can be used in a chain to perform multiple filtering actions.
  85. .. _topic-logging-parts-formatters:
  86. Formatters
  87. ~~~~~~~~~~
  88. Ultimately, a log record needs to be rendered as text. *Formatters*
  89. describe the exact format of that text. A formatter usually consists
  90. of a Python formatting string containing
  91. :ref:`LogRecord attributes <python:logrecord-attributes>`; however,
  92. you can also write custom formatters to implement specific formatting behavior.
  93. .. _logging-security-implications:
  94. Security implications
  95. =====================
  96. The logging system handles potentially sensitive information. For example, the
  97. log record may contain information about a web request or a stack trace, while
  98. some of the data you collect in your own loggers may also have security
  99. implications. You need to be sure you know:
  100. * what information is collected
  101. * where it will subsequently be stored
  102. * how it will be transferred
  103. * who might have access to it.
  104. To help control the collection of sensitive information, you can explicitly
  105. designate certain sensitive information to be filtered out of error reports --
  106. read more about how to :ref:`filter error reports <filtering-error-reports>`.
  107. ``AdminEmailHandler``
  108. ---------------------
  109. The built-in :class:`~django.utils.log.AdminEmailHandler` deserves a mention in
  110. the context of security. If its ``include_html`` option is enabled, the email
  111. message it sends will contain a full traceback, with names and values of local
  112. variables at each level of the stack, plus the values of your Django settings
  113. (in other words, the same level of detail that is exposed in a web page when
  114. :setting:`DEBUG` is ``True``).
  115. It's generally not considered a good idea to send such potentially sensitive
  116. information over email. Consider instead using one of the many third-party
  117. services to which detailed logs can be sent to get the best of multiple worlds
  118. -- the rich information of full tracebacks, clear management of who is notified
  119. and has access to the information, and so on.
  120. .. _configuring-logging:
  121. Configuring logging
  122. ===================
  123. Python's logging library provides several techniques to configure
  124. logging, ranging from a programmatic interface to configuration files.
  125. By default, Django uses the :ref:`dictConfig format
  126. <logging-config-dictschema>`.
  127. In order to configure logging, you use :setting:`LOGGING` to define a
  128. dictionary of logging settings. These settings describe the loggers,
  129. handlers, filters and formatters that you want in your logging setup,
  130. and the log levels and other properties that you want those components
  131. to have.
  132. By default, the :setting:`LOGGING` setting is merged with :ref:`Django's
  133. default logging configuration <default-logging-configuration>` using the
  134. following scheme.
  135. If the ``disable_existing_loggers`` key in the :setting:`LOGGING` dictConfig is
  136. set to ``True`` (which is the ``dictConfig`` default if the key is missing)
  137. then all loggers from the default configuration will be disabled. Disabled
  138. loggers are not the same as removed; the logger will still exist, but will
  139. silently discard anything logged to it, not even propagating entries to a
  140. parent logger. Thus you should be very careful using
  141. ``'disable_existing_loggers': True``; it's probably not what you want. Instead,
  142. you can set ``disable_existing_loggers`` to ``False`` and redefine some or all
  143. of the default loggers; or you can set :setting:`LOGGING_CONFIG` to ``None``
  144. and :ref:`handle logging config yourself <disabling-logging-configuration>`.
  145. Logging is configured as part of the general Django ``setup()`` function.
  146. Therefore, you can be certain that loggers are always ready for use in your
  147. project code.
  148. Examples
  149. --------
  150. The full documentation for :ref:`dictConfig format <logging-config-dictschema>`
  151. is the best source of information about logging configuration dictionaries.
  152. However, to give you a taste of what is possible, here are several examples.
  153. To begin, here's a small configuration that will allow you to output all log
  154. messages to the console:
  155. .. code-block:: python
  156. :caption: ``settings.py``
  157. import os
  158. LOGGING = {
  159. "version": 1,
  160. "disable_existing_loggers": False,
  161. "handlers": {
  162. "console": {
  163. "class": "logging.StreamHandler",
  164. },
  165. },
  166. "root": {
  167. "handlers": ["console"],
  168. "level": "WARNING",
  169. },
  170. }
  171. This configures the parent ``root`` logger to send messages with the
  172. ``WARNING`` level and higher to the console handler. By adjusting the level to
  173. ``INFO`` or ``DEBUG`` you can display more messages. This may be useful during
  174. development.
  175. Next we can add more fine-grained logging. Here's an example of how to make the
  176. logging system print more messages from just the :ref:`django-logger` named
  177. logger:
  178. .. code-block:: python
  179. :caption: ``settings.py``
  180. import os
  181. LOGGING = {
  182. "version": 1,
  183. "disable_existing_loggers": False,
  184. "handlers": {
  185. "console": {
  186. "class": "logging.StreamHandler",
  187. },
  188. },
  189. "root": {
  190. "handlers": ["console"],
  191. "level": "WARNING",
  192. },
  193. "loggers": {
  194. "django": {
  195. "handlers": ["console"],
  196. "level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
  197. "propagate": False,
  198. },
  199. },
  200. }
  201. By default, this config sends messages from the ``django`` logger of level
  202. ``INFO`` or higher to the console. This is the same level as Django's default
  203. logging config, except that the default config only displays log records when
  204. ``DEBUG=True``. Django does not log many such ``INFO`` level messages. With
  205. this config, however, you can also set the environment variable
  206. ``DJANGO_LOG_LEVEL=DEBUG`` to see all of Django's debug logging which is very
  207. verbose as it includes all database queries.
  208. You don't have to log to the console. Here's a configuration which writes all
  209. logging from the :ref:`django-logger` named logger to a local file:
  210. .. code-block:: python
  211. :caption: ``settings.py``
  212. LOGGING = {
  213. "version": 1,
  214. "disable_existing_loggers": False,
  215. "handlers": {
  216. "file": {
  217. "level": "DEBUG",
  218. "class": "logging.FileHandler",
  219. "filename": "/path/to/django/debug.log",
  220. },
  221. },
  222. "loggers": {
  223. "django": {
  224. "handlers": ["file"],
  225. "level": "DEBUG",
  226. "propagate": True,
  227. },
  228. },
  229. }
  230. If you use this example, be sure to change the ``'filename'`` path to a
  231. location that's writable by the user that's running the Django application.
  232. Finally, here's an example of a fairly complex logging setup:
  233. .. code-block:: python
  234. :caption: ``settings.py``
  235. LOGGING = {
  236. "version": 1,
  237. "disable_existing_loggers": False,
  238. "formatters": {
  239. "verbose": {
  240. "format": "{levelname} {asctime} {module} {process:d} {thread:d} {message}",
  241. "style": "{",
  242. },
  243. "simple": {
  244. "format": "{levelname} {message}",
  245. "style": "{",
  246. },
  247. },
  248. "filters": {
  249. "special": {
  250. "()": "project.logging.SpecialFilter",
  251. "foo": "bar",
  252. },
  253. "require_debug_true": {
  254. "()": "django.utils.log.RequireDebugTrue",
  255. },
  256. },
  257. "handlers": {
  258. "console": {
  259. "level": "INFO",
  260. "filters": ["require_debug_true"],
  261. "class": "logging.StreamHandler",
  262. "formatter": "simple",
  263. },
  264. "mail_admins": {
  265. "level": "ERROR",
  266. "class": "django.utils.log.AdminEmailHandler",
  267. "filters": ["special"],
  268. },
  269. },
  270. "loggers": {
  271. "django": {
  272. "handlers": ["console"],
  273. "propagate": True,
  274. },
  275. "django.request": {
  276. "handlers": ["mail_admins"],
  277. "level": "ERROR",
  278. "propagate": False,
  279. },
  280. "myproject.custom": {
  281. "handlers": ["console", "mail_admins"],
  282. "level": "INFO",
  283. "filters": ["special"],
  284. },
  285. },
  286. }
  287. This logging configuration does the following things:
  288. * Identifies the configuration as being in 'dictConfig version 1'
  289. format. At present, this is the only dictConfig format version.
  290. * Defines two formatters:
  291. * ``simple``, that outputs the log level name (e.g., ``DEBUG``) and the log
  292. message.
  293. The ``format`` string is a normal Python formatting string
  294. describing the details that are to be output on each logging
  295. line. The full list of detail that can be output can be
  296. found in :ref:`formatter-objects`.
  297. * ``verbose``, that outputs the log level name, the log
  298. message, plus the time, process, thread and module that
  299. generate the log message.
  300. * Defines two filters:
  301. * ``project.logging.SpecialFilter``, using the alias ``special``. If this
  302. filter required additional arguments, they can be provided as additional
  303. keys in the filter configuration dictionary. In this case, the argument
  304. ``foo`` will be given a value of ``bar`` when instantiating
  305. ``SpecialFilter``.
  306. * ``django.utils.log.RequireDebugTrue``, which passes on records when
  307. :setting:`DEBUG` is ``True``.
  308. * Defines two handlers:
  309. * ``console``, a :class:`~logging.StreamHandler`, which prints any ``INFO``
  310. (or higher) message to ``sys.stderr``. This handler uses the ``simple``
  311. output format.
  312. * ``mail_admins``, an :class:`~django.utils.log.AdminEmailHandler`, which
  313. emails any ``ERROR`` (or higher) message to the site :setting:`ADMINS`.
  314. This handler uses the ``special`` filter.
  315. * Configures three loggers:
  316. * ``django``, which passes all messages to the ``console`` handler.
  317. * ``django.request``, which passes all ``ERROR`` messages to
  318. the ``mail_admins`` handler. In addition, this logger is
  319. marked to *not* propagate messages. This means that log
  320. messages written to ``django.request`` will not be handled
  321. by the ``django`` logger.
  322. * ``myproject.custom``, which passes all messages at ``INFO``
  323. or higher that also pass the ``special`` filter to two
  324. handlers -- the ``console``, and ``mail_admins``. This
  325. means that all ``INFO`` level messages (or higher) will be
  326. printed to the console; ``ERROR`` and ``CRITICAL``
  327. messages will also be output via email.
  328. Custom logging configuration
  329. ----------------------------
  330. If you don't want to use Python's dictConfig format to configure your
  331. logger, you can specify your own configuration scheme.
  332. The :setting:`LOGGING_CONFIG` setting defines the callable that will
  333. be used to configure Django's loggers. By default, it points at
  334. Python's :func:`logging.config.dictConfig()` function. However, if you want to
  335. use a different configuration process, you can use any other callable
  336. that takes a single argument. The contents of :setting:`LOGGING` will
  337. be provided as the value of that argument when logging is configured.
  338. .. _disabling-logging-configuration:
  339. Disabling logging configuration
  340. -------------------------------
  341. If you don't want to configure logging at all (or you want to manually
  342. configure logging using your own approach), you can set
  343. :setting:`LOGGING_CONFIG` to ``None``. This will disable the
  344. configuration process for :ref:`Django's default logging
  345. <default-logging-configuration>`.
  346. Setting :setting:`LOGGING_CONFIG` to ``None`` only means that the automatic
  347. configuration process is disabled, not logging itself. If you disable the
  348. configuration process, Django will still make logging calls, falling back to
  349. whatever default logging behavior is defined.
  350. Here's an example that disables Django's logging configuration and then
  351. manually configures logging:
  352. .. code-block:: python
  353. :caption: ``settings.py``
  354. LOGGING_CONFIG = None
  355. import logging.config
  356. logging.config.dictConfig(...)
  357. Note that the default configuration process only calls
  358. :setting:`LOGGING_CONFIG` once settings are fully-loaded. In contrast, manually
  359. configuring the logging in your settings file will load your logging config
  360. immediately. As such, your logging config must appear *after* any settings on
  361. which it depends.