-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttplogger.py
More file actions
60 lines (53 loc) · 2.14 KB
/
Copy pathhttplogger.py
File metadata and controls
60 lines (53 loc) · 2.14 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
# -*- coding: utf-8 -*-
import logging
import sys
import cherrypy
from cherrypy import _cplogging, _cperror
from django.http import HttpResponseServerError
class HTTPLogger(_cplogging.LogManager):
def __init__(self, app):
_cplogging.LogManager.__init__(self, id(self), cherrypy.log.logger_root)
self.app = app
def __call__(self, environ, start_response):
"""
Called as part of the WSGI stack to log the incoming request
and its response using the common log format. If an error bubbles up
to this middleware, we log it as such.
"""
try:
response = self.app(environ, start_response)
self.access(environ, response)
return response
except:
self.error(traceback=True)
return HttpResponseServerError(_cperror.format_exc())
def access(self, environ, response):
"""
Special method that logs a request following the common
log format. This is mostly taken from CherryPy and adapted
to the WSGI's style of passing information.
"""
if 'status_code' not in dir(response):
return
atoms = {'h': environ.get('REMOTE_ADDR', ''),
'l': '-',
'u': "-",
't': self.time(),
'r': "%s %s %s" % (environ['REQUEST_METHOD'], environ['REQUEST_URI'], environ['SERVER_PROTOCOL']),
's': response.status_code,
'b': str(len(response.content)),
'f': environ.get('HTTP_REFERER', ''),
'a': environ.get('HTTP_USER_AGENT', '')
}
for k, v in atoms.items():
if not isinstance(v, str):
v = str(v)
# Fortunately, repr(str) escapes unprintable chars, \n, \t, etc
# and backslash for us. All we have to do is strip the quotes.
v = repr(v)[1:-1]
# Escape double-quote.
atoms[k] = v.replace('"', '\\"')
try:
self.access_log.log(logging.INFO, self.access_log_format.format(**atoms))
except:
self.error(traceback=True)