logging.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. =======
  2. Logging
  3. =======
  4. .. module:: django.utils.log
  5. :synopsis: Logging tools for Django applications
  6. A quick logging primer
  7. ======================
  8. Django uses Python's builtin :mod:`logging` module to perform system logging.
  9. The usage of this module is discussed in detail in Python's own documentation.
  10. However, if you've never used Python's logging framework (or even if you have),
  11. here's a quick primer.
  12. The cast of players
  13. -------------------
  14. A Python logging configuration consists of four parts:
  15. * :ref:`topic-logging-parts-loggers`
  16. * :ref:`topic-logging-parts-handlers`
  17. * :ref:`topic-logging-parts-filters`
  18. * :ref:`topic-logging-parts-formatters`
  19. .. _topic-logging-parts-loggers:
  20. Loggers
  21. ~~~~~~~
  22. A logger is the entry point into the logging system. Each logger is
  23. a named bucket to which messages can be written for processing.
  24. A logger is configured to have a *log level*. This log level describes
  25. the severity of the messages that the logger will handle. Python
  26. defines the following log levels:
  27. * ``DEBUG``: Low level system information for debugging purposes
  28. * ``INFO``: General system information
  29. * ``WARNING``: Information describing a minor problem that has
  30. occurred.
  31. * ``ERROR``: Information describing a major problem that has
  32. occurred.
  33. * ``CRITICAL``: Information describing a critical problem that has
  34. occurred.
  35. Each message that is written to the logger is a *Log Record*. Each log
  36. record also has a *log level* indicating the severity of that specific
  37. message. A log record can also contain useful metadata that describes
  38. the event that is being logged. This can include details such as a
  39. stack trace or an error code.
  40. When a message is given to the logger, the log level of the message is
  41. compared to the log level of the logger. If the log level of the
  42. message meets or exceeds the log level of the logger itself, the
  43. message will undergo further processing. If it doesn't, the message
  44. will be ignored.
  45. Once a logger has determined that a message needs to be processed,
  46. it is passed to a *Handler*.
  47. .. _topic-logging-parts-handlers:
  48. Handlers
  49. ~~~~~~~~
  50. The handler is the engine that determines what happens to each message
  51. in a logger. It describes a particular logging behavior, such as
  52. writing a message to the screen, to a file, or to a network socket.
  53. Like loggers, handlers also have a log level. If the log level of a
  54. log record doesn't meet or exceed the level of the handler, the
  55. handler will ignore the message.
  56. A logger can have multiple handlers, and each handler can have a
  57. different log level. In this way, it is possible to provide different
  58. forms of notification depending on the importance of a message. For
  59. example, you could install one handler that forwards ``ERROR`` and
  60. ``CRITICAL`` messages to a paging service, while a second handler
  61. logs all messages (including ``ERROR`` and ``CRITICAL`` messages) to a
  62. file for later analysis.
  63. .. _topic-logging-parts-filters:
  64. Filters
  65. ~~~~~~~
  66. A filter is used to provide additional control over which log records
  67. are passed from logger to handler.
  68. By default, any log message that meets log level requirements will be
  69. handled. However, by installing a filter, you can place additional
  70. criteria on the logging process. For example, you could install a
  71. filter that only allows ``ERROR`` messages from a particular source to
  72. be emitted.
  73. Filters can also be used to modify the logging record prior to being
  74. emitted. For example, you could write a filter that downgrades
  75. ``ERROR`` log records to ``WARNING`` records if a particular set of
  76. criteria are met.
  77. Filters can be installed on loggers or on handlers; multiple filters
  78. can be used in a chain to perform multiple filtering actions.
  79. .. _topic-logging-parts-formatters:
  80. Formatters
  81. ~~~~~~~~~~
  82. Ultimately, a log record needs to be rendered as text. Formatters
  83. describe the exact format of that text. A formatter usually consists
  84. of a Python formatting string; however, you can also write custom
  85. formatters to implement specific formatting behavior.
  86. Using logging
  87. =============
  88. Once you have configured your loggers, handlers, filters and
  89. formatters, you need to place logging calls into your code. Using the
  90. logging framework is very simple. Here's an example::
  91. # import the logging library
  92. import logging
  93. # Get an instance of a logger
  94. logger = logging.getLogger(__name__)
  95. def my_view(request, arg1, arg):
  96. ...
  97. if bad_mojo:
  98. # Log an error message
  99. logger.error('Something went wrong!')
  100. And that's it! Every time the ``bad_mojo`` condition is activated, an
  101. error log record will be written.
  102. Naming loggers
  103. --------------
  104. The call to :meth:`logging.getLogger()` obtains (creating, if
  105. necessary) an instance of a logger. The logger instance is identified
  106. by a name. This name is used to identify the logger for configuration
  107. purposes.
  108. By convention, the logger name is usually ``__name__``, the name of
  109. the python module that contains the logger. This allows you to filter
  110. and handle logging calls on a per-module basis. However, if you have
  111. some other way of organizing your logging messages, you can provide
  112. any dot-separated name to identify your logger::
  113. # Get an instance of a specific named logger
  114. logger = logging.getLogger('project.interesting.stuff')
  115. The dotted paths of logger names define a hierarchy. The
  116. ``project.interesting`` logger is considered to be a parent of the
  117. ``project.interesting.stuff`` logger; the ``project`` logger
  118. is a parent of the ``project.interesting`` logger.
  119. Why is the hierarchy important? Well, because loggers can be set to
  120. *propagate* their logging calls to their parents. In this way, you can
  121. define a single set of handlers at the root of a logger tree, and
  122. capture all logging calls in the subtree of loggers. A logging handler
  123. defined in the ``project`` namespace will catch all logging messages
  124. issued on the ``project.interesting`` and
  125. ``project.interesting.stuff`` loggers.
  126. This propagation can be controlled on a per-logger basis. If
  127. you don't want a particular logger to propagate to it's parents, you
  128. can turn off this behavior.
  129. Making logging calls
  130. --------------------
  131. The logger instance contains an entry method for each of the default
  132. log levels:
  133. * ``logger.critical()``
  134. * ``logger.error()``
  135. * ``logger.warning()``
  136. * ``logger.info()``
  137. * ``logger.debug()``
  138. There are two other logging calls available:
  139. * ``logger.log()``: Manually emits a logging message with a
  140. specific log level.
  141. * ``logger.exception()``: Creates an ``ERROR`` level logging
  142. message wrapping the current exception stack frame.
  143. .. _configuring-logging:
  144. Configuring logging
  145. ===================
  146. Of course, it isn't enough to just put logging calls into your code.
  147. You also need to configure the loggers, handlers, filters and
  148. formatters to ensure that logging output is output in a useful way.
  149. Python's logging library provides several techniques to configure
  150. logging, ranging from a programmatic interface to configuration files.
  151. By default, Django uses the `dictConfig format`_.
  152. .. note::
  153. ``logging.dictConfig`` is a builtin library in Python 2.7. In
  154. order to make this library available for users of earlier Python
  155. versions, Django includes a copy as part of ``django.utils.log``.
  156. If you have Python 2.7 or later, the system native library will be used; if
  157. you have Python 2.6, Django's copy will be used.
  158. In order to configure logging, you use :setting:`LOGGING` to define a
  159. dictionary of logging settings. These settings describes the loggers,
  160. handlers, filters and formatters that you want in your logging setup,
  161. and the log levels and other properties that you want those components
  162. to have.
  163. Prior to Django 1.5, the :setting:`LOGGING` setting overwrote the :ref:`default
  164. Django logging configuration <default-logging-configuration>`. From Django
  165. 1.5 forward, the project's logging configuration is merged with Django's
  166. defaults, hence you can decide if you want to add to, or replace the existing
  167. configuration. To completely override the default configuration, set the
  168. ``disable_existing_loggers`` key to True in the :setting:`LOGGING`
  169. dictConfig. Alternatively you can redefine some or all of the loggers.
  170. Logging is configured as soon as settings have been loaded
  171. (either manually using :func:`~django.conf.settings.configure` or when at least
  172. one setting is accessed). Since the loading of settings is one of the first
  173. things that Django does, you can be certain that loggers are always ready for
  174. use in your project code.
  175. .. _dictConfig format: http://docs.python.org/library/logging.config.html#configuration-dictionary-schema
  176. .. _a third-party library: http://bitbucket.org/vinay.sajip/dictconfig
  177. An example
  178. ----------
  179. The full documentation for `dictConfig format`_ is the best source of
  180. information about logging configuration dictionaries. However, to give
  181. you a taste of what is possible, here is an example of a fairly
  182. complex logging setup, configured using :meth:`logging.dictConfig`::
  183. LOGGING = {
  184. 'version': 1,
  185. 'disable_existing_loggers': True,
  186. 'formatters': {
  187. 'verbose': {
  188. 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
  189. },
  190. 'simple': {
  191. 'format': '%(levelname)s %(message)s'
  192. },
  193. },
  194. 'filters': {
  195. 'special': {
  196. '()': 'project.logging.SpecialFilter',
  197. 'foo': 'bar',
  198. }
  199. },
  200. 'handlers': {
  201. 'null': {
  202. 'level': 'DEBUG',
  203. 'class': 'django.utils.log.NullHandler',
  204. },
  205. 'console':{
  206. 'level': 'DEBUG',
  207. 'class': 'logging.StreamHandler',
  208. 'formatter': 'simple'
  209. },
  210. 'mail_admins': {
  211. 'level': 'ERROR',
  212. 'class': 'django.utils.log.AdminEmailHandler',
  213. 'filters': ['special']
  214. }
  215. },
  216. 'loggers': {
  217. 'django': {
  218. 'handlers': ['null'],
  219. 'propagate': True,
  220. 'level': 'INFO',
  221. },
  222. 'django.request': {
  223. 'handlers': ['mail_admins'],
  224. 'level': 'ERROR',
  225. 'propagate': False,
  226. },
  227. 'myproject.custom': {
  228. 'handlers': ['console', 'mail_admins'],
  229. 'level': 'INFO',
  230. 'filters': ['special']
  231. }
  232. }
  233. }
  234. This logging configuration does the following things:
  235. * Identifies the configuration as being in 'dictConfig version 1'
  236. format. At present, this is the only dictConfig format version.
  237. * Disables all existing logging configurations.
  238. * Defines two formatters:
  239. * ``simple``, that just outputs the log level name (e.g.,
  240. ``DEBUG``) and the log message.
  241. The `format` string is a normal Python formatting string
  242. describing the details that are to be output on each logging
  243. line. The full list of detail that can be output can be
  244. found in the `formatter documentation`_.
  245. * ``verbose``, that outputs the log level name, the log
  246. message, plus the time, process, thread and module that
  247. generate the log message.
  248. * Defines one filter -- :class:`project.logging.SpecialFilter`,
  249. using the alias ``special``. If this filter required additional
  250. arguments at time of construction, they can be provided as
  251. additional keys in the filter configuration dictionary. In this
  252. case, the argument ``foo`` will be given a value of ``bar`` when
  253. instantiating the :class:`SpecialFilter`.
  254. * Defines three handlers:
  255. * ``null``, a NullHandler, which will pass any ``DEBUG`` (or
  256. higher) message to ``/dev/null``.
  257. * ``console``, a StreamHandler, which will print any ``DEBUG``
  258. (or higher) message to stderr. This handler uses the `simple` output
  259. format.
  260. * ``mail_admins``, an AdminEmailHandler, which will email any
  261. ``ERROR`` (or higher) message to the site admins. This handler uses
  262. the ``special`` filter.
  263. * Configures three loggers:
  264. * ``django``, which passes all messages at ``INFO`` or higher
  265. to the ``null`` handler.
  266. * ``django.request``, which passes all ``ERROR`` messages to
  267. the ``mail_admins`` handler. In addition, this logger is
  268. marked to *not* propagate messages. This means that log
  269. messages written to ``django.request`` will not be handled
  270. by the ``django`` logger.
  271. * ``myproject.custom``, which passes all messages at ``INFO``
  272. or higher that also pass the ``special`` filter to two
  273. handlers -- the ``console``, and ``mail_admins``. This
  274. means that all ``INFO`` level messages (or higher) will be
  275. printed to the console; ``ERROR`` and ``CRITICAL``
  276. messages will also be output via email.
  277. .. _formatter documentation: http://docs.python.org/library/logging.html#formatter-objects
  278. Custom logging configuration
  279. ----------------------------
  280. If you don't want to use Python's dictConfig format to configure your
  281. logger, you can specify your own configuration scheme.
  282. The :setting:`LOGGING_CONFIG` setting defines the callable that will
  283. be used to configure Django's loggers. By default, it points at
  284. Python's :meth:`logging.dictConfig()` method. However, if you want to
  285. use a different configuration process, you can use any other callable
  286. that takes a single argument. The contents of :setting:`LOGGING` will
  287. be provided as the value of that argument when logging is configured.
  288. Disabling logging configuration
  289. -------------------------------
  290. If you don't want to configure logging at all (or you want to manually
  291. configure logging using your own approach), you can set
  292. :setting:`LOGGING_CONFIG` to ``None``. This will disable the
  293. configuration process.
  294. .. note::
  295. Setting :setting:`LOGGING_CONFIG` to ``None`` only means that the
  296. configuration process is disabled, not logging itself. If you
  297. disable the configuration process, Django will still make logging
  298. calls, falling back to whatever default logging behavior is
  299. defined.
  300. Django's logging extensions
  301. ===========================
  302. Django provides a number of utilities to handle the unique
  303. requirements of logging in Web server environment.
  304. Loggers
  305. -------
  306. Django provides three built-in loggers.
  307. ``django``
  308. ~~~~~~~~~~
  309. ``django`` is the catch-all logger. No messages are posted directly to
  310. this logger.
  311. ``django.request``
  312. ~~~~~~~~~~~~~~~~~~
  313. Log messages related to the handling of requests. 5XX responses are
  314. raised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``
  315. messages.
  316. Messages to this logger have the following extra context:
  317. * ``status_code``: The HTTP response code associated with the
  318. request.
  319. * ``request``: The request object that generated the logging
  320. message.
  321. ``django.db.backends``
  322. ~~~~~~~~~~~~~~~~~~~~~~
  323. Messages relating to the interaction of code with the database.
  324. For example, every SQL statement executed by a request is logged
  325. at the ``DEBUG`` level to this logger.
  326. Messages to this logger have the following extra context:
  327. * ``duration``: The time taken to execute the SQL statement.
  328. * ``sql``: The SQL statement that was executed.
  329. * ``params``: The parameters that were used in the SQL call.
  330. For performance reasons, SQL logging is only enabled when
  331. ``settings.DEBUG`` is set to ``True``, regardless of the logging
  332. level or handlers that are installed.
  333. Handlers
  334. --------
  335. Django provides one log handler in addition to those provided by the
  336. Python logging module.
  337. .. class:: AdminEmailHandler(include_html=False, email_backend=None)
  338. This handler sends an email to the site admins for each log
  339. message it receives.
  340. If the log record contains a ``request`` attribute, the full details
  341. of the request will be included in the email.
  342. If the log record contains stack trace information, that stack
  343. trace will be included in the email.
  344. The ``include_html`` argument of ``AdminEmailHandler`` is used to
  345. control whether the traceback email includes an HTML attachment
  346. containing the full content of the debug Web page that would have been
  347. produced if :setting:`DEBUG` were ``True``. To set this value in your
  348. configuration, include it in the handler definition for
  349. ``django.utils.log.AdminEmailHandler``, like this::
  350. 'handlers': {
  351. 'mail_admins': {
  352. 'level': 'ERROR',
  353. 'class': 'django.utils.log.AdminEmailHandler',
  354. 'include_html': True,
  355. }
  356. },
  357. Note that this HTML version of the email contains a full traceback,
  358. with names and values of local variables at each level of the stack, plus
  359. the values of your Django settings. This information is potentially very
  360. sensitive, and you may not want to send it over email. Consider using
  361. something such as `Sentry`_ to get the best of both worlds -- the
  362. rich information of full tracebacks plus the security of *not* sending the
  363. information over email. You may also explicitly designate certain
  364. sensitive information to be filtered out of error reports -- learn more on
  365. :ref:`Filtering error reports<filtering-error-reports>`.
  366. .. versionadded:: 1.6
  367. By setting the ``email_backend`` argument of ``AdminEmailHandler``, the
  368. :ref:`email backend <topic-email-backends>` that is being used by the
  369. handler can be overridden, like this::
  370. 'handlers': {
  371. 'mail_admins': {
  372. 'level': 'ERROR',
  373. 'class': 'django.utils.log.AdminEmailHandler',
  374. 'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
  375. }
  376. },
  377. By default, an instance of the email backend specified in
  378. :setting:`EMAIL_BACKEND` will be used.
  379. .. _Sentry: http://pypi.python.org/pypi/sentry
  380. Filters
  381. -------
  382. Django provides two log filters in addition to those provided by the Python
  383. logging module.
  384. .. class:: CallbackFilter(callback)
  385. .. versionadded:: 1.4
  386. This filter accepts a callback function (which should accept a single
  387. argument, the record to be logged), and calls it for each record that passes
  388. through the filter. Handling of that record will not proceed if the callback
  389. returns False.
  390. For instance, to filter out :class:`~django.http.UnreadablePostError`
  391. (raised when a user cancels an upload) from the admin emails, you would
  392. create a filter function::
  393. from django.http import UnreadablePostError
  394. def skip_unreadable_post(record):
  395. if record.exc_info:
  396. exc_type, exc_value = record.exc_info[:2]
  397. if isinstance(exc_value, UnreadablePostError):
  398. return False
  399. return True
  400. and then add it to your logging config::
  401. 'filters': {
  402. 'skip_unreadable_posts': {
  403. '()': 'django.utils.log.CallbackFilter',
  404. 'callback': skip_unreadable_post,
  405. }
  406. },
  407. 'handlers': {
  408. 'mail_admins': {
  409. 'level': 'ERROR',
  410. 'filters': ['skip_unreadable_posts'],
  411. 'class': 'django.utils.log.AdminEmailHandler'
  412. }
  413. },
  414. .. class:: RequireDebugFalse()
  415. .. versionadded:: 1.4
  416. This filter will only pass on records when settings.DEBUG is False.
  417. This filter is used as follows in the default :setting:`LOGGING`
  418. configuration to ensure that the :class:`AdminEmailHandler` only sends error
  419. emails to admins when :setting:`DEBUG` is `False`::
  420. 'filters': {
  421. 'require_debug_false': {
  422. '()': 'django.utils.log.RequireDebugFalse',
  423. }
  424. },
  425. 'handlers': {
  426. 'mail_admins': {
  427. 'level': 'ERROR',
  428. 'filters': ['require_debug_false'],
  429. 'class': 'django.utils.log.AdminEmailHandler'
  430. }
  431. },
  432. .. class:: RequireDebugTrue()
  433. .. versionadded:: 1.5
  434. This filter is similar to :class:`RequireDebugFalse`, except that records are
  435. passed only when :setting:`DEBUG` is `True`.
  436. .. _default-logging-configuration:
  437. Django's default logging configuration
  438. ======================================
  439. By default, Django configures the ``django.request`` logger so that all messages
  440. with ``ERROR`` or ``CRITICAL`` level are sent to :class:`AdminEmailHandler`, as
  441. long as the :setting:`DEBUG` setting is set to ``False``.
  442. All messages reaching the ``django`` catch-all logger when :setting:`DEBUG` is
  443. `True` are sent ot the console. They are simply discarded (sent to
  444. ``NullHandler``) when :setting:`DEBUG` is `False`.
  445. .. versionchanged:: 1.5
  446. Before Django 1.5, all messages reaching the ``django`` logger were
  447. discarded, regardless of :setting:`DEBUG`.
  448. See also :ref:`Configuring logging <configuring-logging>` to learn how you can
  449. complement or replace this default logging configuration.