Login

Log errors to a file

Author:
kcarnold
Posted:
March 10, 2008
Language:
Python
Version:
.96
Tags:
middleware log error exception file
Score:
0 (after 0 ratings)

This is another example use of the exception middleware. It shows how to log exceptions to a file. Someone wanted to do this to avoid DOS-ing the email server in case of a silly error.

(untested.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from django.conf import settings
from snippet 638 import StandardExceptionMiddleware, _get_traceback

class FileExceptionLoggerMiddleware(StandardExceptionMiddleware):
    def log_exception(self, request, exception, exc_info):
        from django.conf import settings
        log = open(settings.ERROR_LOG_FILE, 'w')

        from datetime import datetime

        log.write('--- Exception ---\n')
        log.write('Date: %s\n' % datetime.now())
        log.write('IP: %s\n' % request.META.get('REMOTE_ADDR'))
        try:
            request_repr = repr(request)
        except:
            request_repr = "Request repr() unavailable"
        log.write('Request: %s\n' % request_repr)
        log.write('Traceback: %s\n' % _get_traceback(exc_info))
        log.write('--- End ---\n\n')
        log.close()

More like this

  1. Log Django exceptions to Apache error log in mod_wsgi by simon 5 years, 10 months ago
  2. Extensible exception handling middleware by kcarnold 7 years, 4 months ago
  3. log django exceptions to file by vaibhav-jain 9 months, 1 week ago
  4. Mail logged errors to administrators by jmillikin 7 years, 2 months ago
  5. Message exception by marinho 6 years, 9 months ago

Comments

ruserious (on April 17, 2008):

so ... the StandardExceptionMiddleware is not defined

#

henrikG (on August 12, 2008):

ruserious, you need to download snippet 638 as well, and then change the "from snippet 638 import..." in this snippet, to whatever you called your file with snippet 638. For example:

from myproject.middleware.snippet_638 import ...

#

Please login first before commenting.