Login

Log errors to a file

Author:
kcarnold
Posted:
March 10, 2008
Language:
Python
Version:
.96
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. FileField having auto upload_to path by junaidmgithub 1 month ago
  2. LazyPrimaryKeyRelatedField by LLyaudet 1 month, 1 week ago
  3. CacheInDictManager by LLyaudet 1 month, 1 week ago
  4. MYSQL Full Text Expression by Bidaya0 1 month, 1 week ago
  5. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 month, 2 weeks 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.