12

Question is much the same as this, however I'm wanting django to log it's verbose request information to my logging.FileHandler - ie rather than having to look at my webservers logs. I've tried and failed to setup the default logger django.requests to write something other than 4xx and 5xx request information to the handlers.

So the conclusion I've come to after going through the docs and fiddling with the loggers and levels is that django does not actually make a lot of log statements - so I'm looking to confirm that django does not internally log non error scenarios for requests.

Community
  • 1
  • 1
markdsievers
  • 7,151
  • 11
  • 51
  • 83

1 Answers1

17

I can't say I did an exhaustive search, but from what I can see at django/core/handlers/base.py of django 1.4.1, the django.request logger is indeed only used for warnings and error conditions (4xx/5xx).

That said, it's trivial to write middleware that will do all manner of logging for you. Something very simple to get you started could be just:

from time import time
from logging import getLogger

class LoggingMiddleware(object):
    def __init__(self):
        # arguably poor taste to use django's logger
        self.logger = getLogger('django.request')

    def process_request(self, request):
        request.timer = time()
        return None

    def process_response(self, request, response):
        self.logger.info(
            '[%s] %s (%.1fs)',
            response.status_code,
            request.get_full_path(),
            time() - request.timer
        )
        return response
Yaniv Aknin
  • 4,103
  • 3
  • 23
  • 29
  • Thanks for the answer. Agreed, custom rolled solution is pretty basic. – markdsievers Oct 17 '12 at 20:22
  • I'm not sure you'll get something else - my answer also mentions that I don't see django doing successful request logging at all... – Yaniv Aknin Oct 17 '12 at 20:32
  • 1
    How are you supposed to integrate this into settings.py? – Giampaolo Rodolà Jan 22 '14 at 08:50
  • 2
    @GiampaoloRodolà add it to `MIDDLEWARE_CLASSES`, ie `MIDDLEWARE_CLASSES += ('myapp.middleware.LoggingMiddleware',)` where the class above is in the file `myapp/middleware.py` – Rebs Dec 04 '15 at 03:46
  • this is outdated. for django 1.10, see http://stackoverflow.com/a/39476411/4744937 – Rex Salisbury Sep 13 '16 at 18:06
  • @RexSalisbury This applies to Django 1.4 and you mention it's outdated and reference Django 1.1? The link resolves to this answer... Much confusion. – markdsievers Oct 11 '16 at 19:49
  • `request.timer` can be non-existent if `process_request` isn't hit for some reason (caching, maybe?). My solution was to change the line to: `time() - request.timer if hasattr(request, 'timer') else 0`. – Colin Basnett Jun 02 '17 at 19:51