logging.txt 18 KB

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