Find file
192 lines (161 sloc) 6.08 KB
from __future__ import unicode_literals
import logging
import logging.config # needed when logging_config doesn't start with logging.config
from copy import copy
from django.conf import settings
from django.core import mail
from django.core.mail import get_connection
from import color_style
from django.utils.module_loading import import_string
from django.views.debug import ExceptionReporter
# Default logging for Django. This sends an email to the site admins on every
# HTTP 500 error. Depending on DEBUG, all other log records are either sent to
# the console (DEBUG=True) or discarded (DEBUG=False) by means of the
# require_debug_true filter.
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
'formatters': {
'django.server': {
'()': 'django.utils.log.ServerFormatter',
'format': '[%(server_time)s] %(message)s',
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'django.server': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'django.server',
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
'loggers': {
'django': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'django.server': {
'handlers': ['django.server'],
'level': 'INFO',
'propagate': False,
def configure_logging(logging_config, logging_settings):
if logging_config:
# First find the logging configuration function ...
logging_config_func = import_string(logging_config)
# ... then invoke it with the logging settings
if logging_settings:
class AdminEmailHandler(logging.Handler):
"""An exception log handler that emails log entries to site admins.
If the request is passed as the first argument to the log record,
request data will be provided in the email report.
def __init__(self, include_html=False, email_backend=None):
self.include_html = include_html
self.email_backend = email_backend
def emit(self, record):
request = record.request
subject = '%s (%s IP): %s' % (
('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
else 'EXTERNAL'),
except Exception:
subject = '%s: %s' % (
request = None
subject = self.format_subject(subject)
# Since we add a nicely formatted traceback on our own, create a copy
# of the log record without the exception data.
no_exc_record = copy(record)
no_exc_record.exc_info = None
no_exc_record.exc_text = None
if record.exc_info:
exc_info = record.exc_info
exc_info = (None, record.getMessage(), None)
reporter = ExceptionReporter(request, is_email=True, *exc_info)
message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text())
html_message = reporter.get_traceback_html() if self.include_html else None
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
def send_mail(self, subject, message, *args, **kwargs):
mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
def connection(self):
return get_connection(backend=self.email_backend, fail_silently=True)
def format_subject(self, subject):
Escape CR and LF characters.
return subject.replace('\n', '\\n').replace('\r', '\\r')
class CallbackFilter(logging.Filter):
A logging filter that checks the return value of a given callable (which
takes the record-to-be-logged as its only parameter) to decide whether to
log a record.
def __init__(self, callback):
self.callback = callback
def filter(self, record):
if self.callback(record):
return 1
return 0
class RequireDebugFalse(logging.Filter):
def filter(self, record):
return not settings.DEBUG
class RequireDebugTrue(logging.Filter):
def filter(self, record):
return settings.DEBUG
class ServerFormatter(logging.Formatter):
def __init__(self, *args, **kwargs): = color_style()
super(ServerFormatter, self).__init__(*args, **kwargs)
def format(self, record):
args = record.args
msg = record.msg
if len(args) == 0:
msg =
if args[1][0] == '2':
# Put 2XX first, since it should be the common case
msg =
elif args[1][0] == '1':
msg =
elif args[1] == '304':
msg =
elif args[1][0] == '3':
msg =
elif args[1] == '404':
msg =
elif args[1][0] == '4':
msg =
# Any 5XX, or any other response
msg =
record.msg = msg
return super(ServerFormatter, self).format(record)