Logging solution for mod_python/FCGI

 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
# 1. In settings.py add something like this:

import logging
logging.basicConfig(
    level=logging.NOTSET,
    format='%(asctime)s %(levelname)-8s %(message)s',
    datefmt='%m-%d %H:%M',
    #change as needed
    filename='/path/to/log/dir/my-log-file.log', 
    filemode='a'
)
logging.getLogger('').setLevel(logging.NOTSET)


# 2. In settings.py add '<myapp>.middleware.trace.TraceMiddleware' 
# to MIDDLEWARE_CLASSES.


# 3. Then in <myapp>/middleware create trace.py:

import logging, datetime

class TraceMiddleware(object):
    def process_request(self, request) :
        logging.info(
            "%s %s" % (request.META['REQUEST_METHOD'],
            request.get_full_path())
        )
        request.started = datetime.datetime.now()
        return None

    def process_response(self, request, response) :
        delta = (datetime.datetime.now() - request.started)
        logging.info(
            "<- Response in: %f sec.",
            delta.seconds + (delta.microseconds / 1000000.0)
        )
        return response

    def process_exception(self, request, exception):
        logging.exception("*** EXCEPTION ***")


# 4. Enjoy luxury of the logging API in your code:

    ....
    logging.debug('Redirecting to the home page')
    return HttpResponseRedirect('/')

More like this

  1. Middleware to log username into apache logs with mod_python by kahless 7 years, 1 month ago
  2. SQL Log To Console Middleware by davepeck 4 years, 8 months ago
  3. Log username in Apache access logs by arthur 4 years, 1 month ago
  4. Twisted protocol for receiving logging module messages over a socket by afternoon 5 years, 6 months ago
  5. Updated - Template context debugger with (I)Pdb by dnordberg 4 years, 8 months ago

Comments

stefan (on September 25, 2007):

request.started does not seem to exist in django, maybe it did sometime? That makes the middleware not very useful. Otherwise, good to know about the logging module

#

pdxwebdev (on February 21, 2011):

This saved me loads of time from having to concentrate while stepping though a deeply recursive method. I was able to easily see that I forgot to import the time module. ha!

#

(Forgotten your password?)