log.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import logging
  2. import logging.config # needed when logging_config doesn't start with logging.config
  3. from copy import copy
  4. from django.conf import settings
  5. from django.core import mail
  6. from django.core.mail import get_connection
  7. from django.core.management.color import color_style
  8. from django.utils.module_loading import import_string
  9. request_logger = logging.getLogger("django.request")
  10. # Default logging for Django. This sends an email to the site admins on every
  11. # HTTP 500 error. Depending on DEBUG, all other log records are either sent to
  12. # the console (DEBUG=True) or discarded (DEBUG=False) by means of the
  13. # require_debug_true filter. This configuration is quoted in
  14. # docs/ref/logging.txt; please amend it there if edited here.
  15. DEFAULT_LOGGING = {
  16. "version": 1,
  17. "disable_existing_loggers": False,
  18. "filters": {
  19. "require_debug_false": {
  20. "()": "django.utils.log.RequireDebugFalse",
  21. },
  22. "require_debug_true": {
  23. "()": "django.utils.log.RequireDebugTrue",
  24. },
  25. },
  26. "formatters": {
  27. "django.server": {
  28. "()": "django.utils.log.ServerFormatter",
  29. "format": "[{server_time}] {message}",
  30. "style": "{",
  31. }
  32. },
  33. "handlers": {
  34. "console": {
  35. "level": "INFO",
  36. "filters": ["require_debug_true"],
  37. "class": "logging.StreamHandler",
  38. },
  39. "django.server": {
  40. "level": "INFO",
  41. "class": "logging.StreamHandler",
  42. "formatter": "django.server",
  43. },
  44. "mail_admins": {
  45. "level": "ERROR",
  46. "filters": ["require_debug_false"],
  47. "class": "django.utils.log.AdminEmailHandler",
  48. },
  49. },
  50. "loggers": {
  51. "django": {
  52. "handlers": ["console", "mail_admins"],
  53. "level": "INFO",
  54. },
  55. "django.server": {
  56. "handlers": ["django.server"],
  57. "level": "INFO",
  58. "propagate": False,
  59. },
  60. },
  61. }
  62. def configure_logging(logging_config, logging_settings):
  63. if logging_config:
  64. # First find the logging configuration function ...
  65. logging_config_func = import_string(logging_config)
  66. logging.config.dictConfig(DEFAULT_LOGGING)
  67. # ... then invoke it with the logging settings
  68. if logging_settings:
  69. logging_config_func(logging_settings)
  70. class AdminEmailHandler(logging.Handler):
  71. """An exception log handler that emails log entries to site admins.
  72. If the request is passed as the first argument to the log record,
  73. request data will be provided in the email report.
  74. """
  75. def __init__(self, include_html=False, email_backend=None, reporter_class=None):
  76. super().__init__()
  77. self.include_html = include_html
  78. self.email_backend = email_backend
  79. self.reporter_class = import_string(
  80. reporter_class or settings.DEFAULT_EXCEPTION_REPORTER
  81. )
  82. def emit(self, record):
  83. # Early return when no email will be sent.
  84. if (
  85. not settings.ADMINS
  86. # Method not overridden.
  87. and self.send_mail.__func__ is AdminEmailHandler.send_mail
  88. ):
  89. return
  90. try:
  91. request = record.request
  92. subject = "%s (%s IP): %s" % (
  93. record.levelname,
  94. (
  95. "internal"
  96. if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS
  97. else "EXTERNAL"
  98. ),
  99. record.getMessage(),
  100. )
  101. except Exception:
  102. subject = "%s: %s" % (record.levelname, record.getMessage())
  103. request = None
  104. subject = self.format_subject(subject)
  105. # Since we add a nicely formatted traceback on our own, create a copy
  106. # of the log record without the exception data.
  107. no_exc_record = copy(record)
  108. no_exc_record.exc_info = None
  109. no_exc_record.exc_text = None
  110. if record.exc_info:
  111. exc_info = record.exc_info
  112. else:
  113. exc_info = (None, record.getMessage(), None)
  114. reporter = self.reporter_class(request, is_email=True, *exc_info)
  115. message = "%s\n\n%s" % (
  116. self.format(no_exc_record),
  117. reporter.get_traceback_text(),
  118. )
  119. html_message = reporter.get_traceback_html() if self.include_html else None
  120. self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  121. def send_mail(self, subject, message, *args, **kwargs):
  122. mail.mail_admins(
  123. subject, message, *args, connection=self.connection(), **kwargs
  124. )
  125. def connection(self):
  126. return get_connection(backend=self.email_backend, fail_silently=True)
  127. def format_subject(self, subject):
  128. """
  129. Escape CR and LF characters.
  130. """
  131. return subject.replace("\n", "\\n").replace("\r", "\\r")
  132. class CallbackFilter(logging.Filter):
  133. """
  134. A logging filter that checks the return value of a given callable (which
  135. takes the record-to-be-logged as its only parameter) to decide whether to
  136. log a record.
  137. """
  138. def __init__(self, callback):
  139. self.callback = callback
  140. def filter(self, record):
  141. if self.callback(record):
  142. return 1
  143. return 0
  144. class RequireDebugFalse(logging.Filter):
  145. def filter(self, record):
  146. return not settings.DEBUG
  147. class RequireDebugTrue(logging.Filter):
  148. def filter(self, record):
  149. return settings.DEBUG
  150. class ServerFormatter(logging.Formatter):
  151. default_time_format = "%d/%b/%Y %H:%M:%S"
  152. def __init__(self, *args, **kwargs):
  153. self.style = color_style()
  154. super().__init__(*args, **kwargs)
  155. def format(self, record):
  156. msg = record.msg
  157. status_code = getattr(record, "status_code", None)
  158. if status_code:
  159. if 200 <= status_code < 300:
  160. # Put 2XX first, since it should be the common case
  161. msg = self.style.HTTP_SUCCESS(msg)
  162. elif 100 <= status_code < 200:
  163. msg = self.style.HTTP_INFO(msg)
  164. elif status_code == 304:
  165. msg = self.style.HTTP_NOT_MODIFIED(msg)
  166. elif 300 <= status_code < 400:
  167. msg = self.style.HTTP_REDIRECT(msg)
  168. elif status_code == 404:
  169. msg = self.style.HTTP_NOT_FOUND(msg)
  170. elif 400 <= status_code < 500:
  171. msg = self.style.HTTP_BAD_REQUEST(msg)
  172. else:
  173. # Any 5XX, or any other status code
  174. msg = self.style.HTTP_SERVER_ERROR(msg)
  175. if self.uses_server_time() and not hasattr(record, "server_time"):
  176. record.server_time = self.formatTime(record, self.datefmt)
  177. record.msg = msg
  178. return super().format(record)
  179. def uses_server_time(self):
  180. return self._fmt.find("{server_time}") >= 0
  181. def log_response(
  182. message,
  183. *args,
  184. response=None,
  185. request=None,
  186. logger=request_logger,
  187. level=None,
  188. exception=None,
  189. ):
  190. """
  191. Log errors based on HttpResponse status.
  192. Log 5xx responses as errors and 4xx responses as warnings (unless a level
  193. is given as a keyword argument). The HttpResponse status_code and the
  194. request are passed to the logger's extra parameter.
  195. """
  196. # Check if the response has already been logged. Multiple requests to log
  197. # the same response can be received in some cases, e.g., when the
  198. # response is the result of an exception and is logged when the exception
  199. # is caught, to record the exception.
  200. if getattr(response, "_has_been_logged", False):
  201. return
  202. if level is None:
  203. if response.status_code >= 500:
  204. level = "error"
  205. elif response.status_code >= 400:
  206. level = "warning"
  207. else:
  208. level = "info"
  209. getattr(logger, level)(
  210. message,
  211. *args,
  212. extra={
  213. "status_code": response.status_code,
  214. "request": request,
  215. },
  216. exc_info=exception,
  217. )
  218. response._has_been_logged = True