Mail logged errors to administrators

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from logging import Formatter, Handler, StreamHandler, getLogger

from django.conf import settings
from django.core.mail import mail_admins

# Define LOG_FORMAT and LOG_ROOTS in your settings.py file.
# LOG_FORMAT is used for formatting error messages: see http://docs.python.org/lib/node406.html
# LOG_ROOTS is an iterable of root logger names that will be caught by this handler.

class RequestFormatter (Formatter):
	def __init__ (self, print_request = True):
		# logging.Formatter is an old-style class
		Formatter.__init__ (self, settings.LOG_FORMAT)
		self.__print_request = print_request
		
	def format (self, record):
		message = Formatter.format (self, record)
		if self.__print_request:
			try:
				request_repr = repr (record.request)
			except Exception:
				request_repr = "Request repr() unavailable"
			message += "\n\n"
			message += request_repr
		return message
		
class MailAdminsHandler (Handler):
	def get_subject (self, record):
		try:
			request = record.request
		except AttributeError:
			return "Error (no request attached)"
		if request.META.get ('REMOTE_ADDR') in settings.INTERNAL_IPS:
			remote_attr = "internal"
		else:
			remote_attr = "EXTERNAL"
		return "Error (%s IP): %s" % (remote_attr, request.path)
		
	def emit (self, record):
		subject = self.get_subject (record)
		message = self.format (record)
		mail_admins (subject, message, fail_silently = True)
		
class LoggingSetupMiddleware (object):
	def __init__ (self):
		if settings.DEBUG:
			handler = StreamHandler ()
			formatter = RequestFormatter (print_request = False)
		else:
			handler = MailAdminsHandler ()
			formatter = RequestFormatter (print_request = True)
			
		handler.setFormatter (formatter)
		for root_name in settings.LOG_ROOTS:
			getLogger (root_name).addHandler (handler)
			

More like this

  1. Log Django exceptions to Apache error log in mod_wsgi by simon 4 years, 7 months ago
  2. Logging Middleware by Magus 6 years, 6 months ago
  3. Log username in Apache access logs by arthur 4 years, 1 month ago
  4. SQL Log To Console Middleware by davepeck 4 years, 8 months ago
  5. Middleware to log username into apache logs with mod_python by kahless 7 years, 1 month ago

Comments

(Forgotten your password?)