Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

log.py 7.8KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. try:
  84. request = record.request
  85. subject = "%s (%s IP): %s" % (
  86. record.levelname,
  87. (
  88. "internal"
  89. if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS
  90. else "EXTERNAL"
  91. ),
  92. record.getMessage(),
  93. )
  94. except Exception:
  95. subject = "%s: %s" % (record.levelname, record.getMessage())
  96. request = None
  97. subject = self.format_subject(subject)
  98. # Since we add a nicely formatted traceback on our own, create a copy
  99. # of the log record without the exception data.
  100. no_exc_record = copy(record)
  101. no_exc_record.exc_info = None
  102. no_exc_record.exc_text = None
  103. if record.exc_info:
  104. exc_info = record.exc_info
  105. else:
  106. exc_info = (None, record.getMessage(), None)
  107. reporter = self.reporter_class(request, is_email=True, *exc_info)
  108. message = "%s\n\n%s" % (
  109. self.format(no_exc_record),
  110. reporter.get_traceback_text(),
  111. )
  112. html_message = reporter.get_traceback_html() if self.include_html else None
  113. self.send_mail(subject, message, fail_silently=True, html_message=html_message)
  114. def send_mail(self, subject, message, *args, **kwargs):
  115. mail.mail_admins(
  116. subject, message, *args, connection=self.connection(), **kwargs
  117. )
  118. def connection(self):
  119. return get_connection(backend=self.email_backend, fail_silently=True)
  120. def format_subject(self, subject):
  121. """
  122. Escape CR and LF characters.
  123. """
  124. return subject.replace("\n", "\\n").replace("\r", "\\r")
  125. class CallbackFilter(logging.Filter):
  126. """
  127. A logging filter that checks the return value of a given callable (which
  128. takes the record-to-be-logged as its only parameter) to decide whether to
  129. log a record.
  130. """
  131. def __init__(self, callback):
  132. self.callback = callback
  133. def filter(self, record):
  134. if self.callback(record):
  135. return 1
  136. return 0
  137. class RequireDebugFalse(logging.Filter):
  138. def filter(self, record):
  139. return not settings.DEBUG
  140. class RequireDebugTrue(logging.Filter):
  141. def filter(self, record):
  142. return settings.DEBUG
  143. class ServerFormatter(logging.Formatter):
  144. default_time_format = "%d/%b/%Y %H:%M:%S"
  145. def __init__(self, *args, **kwargs):
  146. self.style = color_style()
  147. super().__init__(*args, **kwargs)
  148. def format(self, record):
  149. msg = record.msg
  150. status_code = getattr(record, "status_code", None)
  151. if status_code:
  152. if 200 <= status_code < 300:
  153. # Put 2XX first, since it should be the common case
  154. msg = self.style.HTTP_SUCCESS(msg)
  155. elif 100 <= status_code < 200:
  156. msg = self.style.HTTP_INFO(msg)
  157. elif status_code == 304:
  158. msg = self.style.HTTP_NOT_MODIFIED(msg)
  159. elif 300 <= status_code < 400:
  160. msg = self.style.HTTP_REDIRECT(msg)
  161. elif status_code == 404:
  162. msg = self.style.HTTP_NOT_FOUND(msg)
  163. elif 400 <= status_code < 500:
  164. msg = self.style.HTTP_BAD_REQUEST(msg)
  165. else:
  166. # Any 5XX, or any other status code
  167. msg = self.style.HTTP_SERVER_ERROR(msg)
  168. if self.uses_server_time() and not hasattr(record, "server_time"):
  169. record.server_time = self.formatTime(record, self.datefmt)
  170. record.msg = msg
  171. return super().format(record)
  172. def uses_server_time(self):
  173. return self._fmt.find("{server_time}") >= 0
  174. def log_response(
  175. message,
  176. *args,
  177. response=None,
  178. request=None,
  179. logger=request_logger,
  180. level=None,
  181. exception=None,
  182. ):
  183. """
  184. Log errors based on HttpResponse status.
  185. Log 5xx responses as errors and 4xx responses as warnings (unless a level
  186. is given as a keyword argument). The HttpResponse status_code and the
  187. request are passed to the logger's extra parameter.
  188. """
  189. # Check if the response has already been logged. Multiple requests to log
  190. # the same response can be received in some cases, e.g., when the
  191. # response is the result of an exception and is logged when the exception
  192. # is caught, to record the exception.
  193. if getattr(response, "_has_been_logged", False):
  194. return
  195. if level is None:
  196. if response.status_code >= 500:
  197. level = "error"
  198. elif response.status_code >= 400:
  199. level = "warning"
  200. else:
  201. level = "info"
  202. getattr(logger, level)(
  203. message,
  204. *args,
  205. extra={
  206. "status_code": response.status_code,
  207. "request": request,
  208. },
  209. exc_info=exception,
  210. )
  211. response._has_been_logged = True