- Author:
- mikeivanov
- Posted:
- September 18, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 1 (after 1 ratings)
The solution is based on dballanc's snippet.
Can easily be combined with any of the SQL tracing solutions.
You might want to run a separate logging server and redirect your logs there. Please refer to the logging reference manual.
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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
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
#
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!
#
Please login first before commenting.