日志

参见

Django’s logging module extends Python’s builtin logging.

Logging is configured as part of the general Django django.setup() function, so it’s always available unless explicitly disabled.

Django’s default logging configuration

By default, Django uses Python’s logging.config.dictConfig format.

Default logging conditions

The full set of default logging conditions are:

When DEBUG is True:

  • The django logger sends messages in the django hierarchy (except django.server) at the INFO level or higher to the console.

When DEBUG is False:

  • The django logger sends messages in the django hierarchy (except django.server) with ERROR or CRITICAL level to AdminEmailHandler.

Independently of the value of DEBUG:

  • The django.server logger sends messages at the INFO level or higher to the console.

All loggers except django.server propagate logging to their parents, up to the root django logger. The console and mail_admins handlers are attached to the root logger to provide the behavior described above.

Python’s own defaults send records of level WARNING and higher to the console.

Default logging definition

Django’s default logging configuration inherits Python’s defaults. It’s available as django.utils.log.DEFAULT_LOGGING and defined in django/utils/log.py:

  1. {
  2. 'version': 1,
  3. 'disable_existing_loggers': False,
  4. 'filters': {
  5. 'require_debug_false': {
  6. '()': 'django.utils.log.RequireDebugFalse',
  7. },
  8. 'require_debug_true': {
  9. '()': 'django.utils.log.RequireDebugTrue',
  10. },
  11. },
  12. 'formatters': {
  13. 'django.server': {
  14. '()': 'django.utils.log.ServerFormatter',
  15. 'format': '[{server_time}] {message}',
  16. 'style': '{',
  17. }
  18. },
  19. 'handlers': {
  20. 'console': {
  21. 'level': 'INFO',
  22. 'filters': ['require_debug_true'],
  23. 'class': 'logging.StreamHandler',
  24. },
  25. 'django.server': {
  26. 'level': 'INFO',
  27. 'class': 'logging.StreamHandler',
  28. 'formatter': 'django.server',
  29. },
  30. 'mail_admins': {
  31. 'level': 'ERROR',
  32. 'filters': ['require_debug_false'],
  33. 'class': 'django.utils.log.AdminEmailHandler'
  34. }
  35. },
  36. 'loggers': {
  37. 'django': {
  38. 'handlers': ['console', 'mail_admins'],
  39. 'level': 'INFO',
  40. },
  41. 'django.server': {
  42. 'handlers': ['django.server'],
  43. 'level': 'INFO',
  44. 'propagate': False,
  45. },
  46. }
  47. }

See 日志模块的配置 on how to complement or replace this default logging configuration.

Django logging extensions

Django provides a number of utilities to handle the particular requirements of logging in a web server environment.

Loggers

Django provides several built-in loggers.

django

The parent logger for messages in the django named logger hierarchy. Django does not post messages using this name. Instead, it uses one of the loggers below.

django.request

Log messages related to the handling of requests. 5XX responses are raised as ERROR messages; 4XX responses are raised as WARNING messages. Requests that are logged to the django.security logger aren’t logged to django.request.

Messages to this logger have the following extra context:

  • status_code: The HTTP response code associated with the request.
  • request: The request object that generated the logging message.

django.server

Log messages related to the handling of requests received by the server invoked by the runserver command. HTTP 5XX responses are logged as ERROR messages, 4XX responses are logged as WARNING messages, and everything else is logged as INFO.

Messages to this logger have the following extra context:

  • status_code: The HTTP response code associated with the request.
  • request: The request object that generated the logging message.

django.template

Log messages related to the rendering of templates.

  • Missing context variables are logged as DEBUG messages.

django.db.backends

Messages relating to the interaction of code with the database. For example, every application-level SQL statement executed by a request is logged at the DEBUG level to this logger.

Messages to this logger have the following extra context:

  • duration: The time taken to execute the SQL statement.
  • sql: The SQL statement that was executed.
  • params: The parameters that were used in the SQL call.
  • alias: The alias of the database used in the SQL call.

For performance reasons, SQL logging is only enabled when settings.DEBUG is set to True, regardless of the logging level or handlers that are installed.

This logging does not include framework-level initialization (e.g. SET TIMEZONE) or transaction management queries (e.g. BEGIN, COMMIT, and ROLLBACK). Turn on query logging in your database if you wish to view all database queries.

Changed in Django 4.0:

The database alias was added to log messages.

django.security.*

The security loggers will receive messages on any occurrence of SuspiciousOperation and other security-related errors. There is a sub-logger for each subtype of security error, including all SuspiciousOperations. The level of the log event depends on where the exception is handled. Most occurrences are logged as a warning, while any SuspiciousOperation that reaches the WSGI handler will be logged as an error. For example, when an HTTP Host header is included in a request from a client that does not match ALLOWED_HOSTS, Django will return a 400 response, and an error message will be logged to the django.security.DisallowedHost logger.

These log events will reach the django logger by default, which mails error events to admins when DEBUG=False. Requests resulting in a 400 response due to a SuspiciousOperation will not be logged to the django.request logger, but only to the django.security logger.

To silence a particular type of SuspiciousOperation, you can override that specific logger following this example:

  1. 'handlers': {
  2. 'null': {
  3. 'class': 'logging.NullHandler',
  4. },
  5. },
  6. 'loggers': {
  7. 'django.security.DisallowedHost': {
  8. 'handlers': ['null'],
  9. 'propagate': False,
  10. },
  11. },

Other django.security loggers not based on SuspiciousOperation are:

django.db.backends.schema

Logs the SQL queries that are executed during schema changes to the database by the migrations framework. Note that it won’t log the queries executed by RunPython. Messages to this logger have params and sql in their extra context (but unlike django.db.backends, not duration). The values have the same meaning as explained in django.db.backends.

Handlers

Django provides one log handler in addition to those provided by the Python logging module.

class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)

This handler sends an email to the site ADMINS for each log message it receives.

If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase “internal IP” if the client’s IP address is in the INTERNAL_IPS setting; if not, it will include “EXTERNAL IP”.

If the log record contains stack trace information, that stack trace will be included in the email.

The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this:

  1. 'handlers': {
  2. 'mail_admins': {
  3. 'level': 'ERROR',
  4. 'class': 'django.utils.log.AdminEmailHandler',
  5. 'include_html': True,
  6. },
  7. },

Be aware of the security implications of logging when using the AdminEmailHandler.

By setting the email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden, like this:

  1. 'handlers': {
  2. 'mail_admins': {
  3. 'level': 'ERROR',
  4. 'class': 'django.utils.log.AdminEmailHandler',
  5. 'email_backend': 'django.core.mail.backends.filebased.EmailBackend',
  6. },
  7. },

By default, an instance of the email backend specified in EMAIL_BACKEND will be used.

The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this:

  1. 'handlers': {
  2. 'mail_admins': {
  3. 'level': 'ERROR',
  4. 'class': 'django.utils.log.AdminEmailHandler',
  5. 'include_html': True,
  6. 'reporter_class': 'somepackage.error_reporter.CustomErrorReporter',
  7. },
  8. },
  • send_mail(subject, message, \args, **kwargs*)

    Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.

过滤器

Django provides some log filters in addition to those provided by the Python logging module.

class CallbackFilter(callback)

This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False.

For instance, to filter out UnreadablePostError (raised when a user cancels an upload) from the admin emails, you would create a filter function:

  1. from django.http import UnreadablePostError
  2. def skip_unreadable_post(record):
  3. if record.exc_info:
  4. exc_type, exc_value = record.exc_info[:2]
  5. if isinstance(exc_value, UnreadablePostError):
  6. return False
  7. return True

and then add it to your logging config:

  1. 'filters': {
  2. 'skip_unreadable_posts': {
  3. '()': 'django.utils.log.CallbackFilter',
  4. 'callback': skip_unreadable_post,
  5. },
  6. },
  7. 'handlers': {
  8. 'mail_admins': {
  9. 'level': 'ERROR',
  10. 'filters': ['skip_unreadable_posts'],
  11. 'class': 'django.utils.log.AdminEmailHandler',
  12. },
  13. },

class RequireDebugFalse

This filter will only pass on records when settings.DEBUG is False.

This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False:

  1. 'filters': {
  2. 'require_debug_false': {
  3. '()': 'django.utils.log.RequireDebugFalse',
  4. },
  5. },
  6. 'handlers': {
  7. 'mail_admins': {
  8. 'level': 'ERROR',
  9. 'filters': ['require_debug_false'],
  10. 'class': 'django.utils.log.AdminEmailHandler',
  11. },
  12. },

class RequireDebugTrue

This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True.