Created
January 20, 2011 20:03
-
-
Save dmpayton/788535 to your computer and use it in GitHub Desktop.
I recently ditched runserver for gunicorn as my dev server. This middleware spits out request info as it comes in to make life a bit easier.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from datetime import datetime | |
from django.conf import settings | |
try: | |
from threading import local | |
except ImportError: | |
from django.utils._threading_local import local | |
_thread_locals = local() | |
REQUEST_LOG = getattr(settings, 'REQUEST_LOG', None) | |
class GunicornRequestOutputMiddleware(object): | |
ignore_paths = [ | |
settings.MEDIA_URL, | |
settings.STATIC_URL, | |
settings.ADMIN_MEDIA_PREFIX, | |
'/favicon.ico', | |
'/__debug__' | |
] | |
def ignore(self, request): | |
for path in self.ignore_paths: | |
if request.path.startswith(path): | |
return True | |
return False | |
def write(self, message): | |
if REQUEST_LOG: | |
request_log = open(REQUEST_LOG, 'a') | |
else: | |
request_log = sys.stdout | |
request_log.write(message + '\n') | |
def process_request(self, request): | |
if not self.ignore(request): | |
now = datetime.now() | |
_thread_locals.start_time = now | |
def process_response(self, request, response): | |
if not self.ignore(request): | |
now = datetime.now() | |
data = { | |
'timestamp': now, | |
'method': request.method, | |
'path': request.path, | |
'timedelta': now - _thread_locals.start_time, | |
'response': response.status_code, | |
'ip': request.META['REMOTE_ADDR'], | |
} | |
if request.GET: | |
data['path'] += '?%s' % request.GET.urlencode() | |
message = '[%(timestamp)s] %(ip)s "%(method)s %(path)s" %(response)s (%(timedelta)s)' % data | |
self.write(message) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment