Login

Mail logged errors to administrators

Author:
jmillikin
Posted:
May 31, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Activate this middleware and define LOG_FORMAT & LOG_ROOTS in your settings.py. Then you can use Python's logging module for easy logging within your application.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.