1 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) |
---|
2 | # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php |
---|
3 | """ |
---|
4 | Middleware for logging requests, using Apache combined log format |
---|
5 | """ |
---|
6 | |
---|
7 | import logging |
---|
8 | import time |
---|
9 | import urllib |
---|
10 | |
---|
11 | class TransLogger(object): |
---|
12 | """ |
---|
13 | This logging middleware will log all requests as they go through. |
---|
14 | They are, by default, sent to a logger named ``'wsgi'`` at the |
---|
15 | INFO level. |
---|
16 | |
---|
17 | If ``setup_console_handler`` is true, then messages for the named |
---|
18 | logger will be sent to the console. |
---|
19 | """ |
---|
20 | |
---|
21 | format = ('%(REMOTE_ADDR)s - %(REMOTE_USER)s [%(time)s] ' |
---|
22 | '"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s" ' |
---|
23 | '%(status)s %(bytes)s "%(HTTP_REFERER)s" "%(HTTP_USER_AGENT)s"') |
---|
24 | |
---|
25 | def __init__(self, application, |
---|
26 | logger=None, |
---|
27 | format=None, |
---|
28 | logging_level=logging.INFO, |
---|
29 | logger_name='wsgi', |
---|
30 | setup_console_handler=True, |
---|
31 | set_logger_level=logging.DEBUG): |
---|
32 | if format is not None: |
---|
33 | self.format = format |
---|
34 | self.application = application |
---|
35 | self.logging_level = logging_level |
---|
36 | self.logger_name = logger_name |
---|
37 | if logger is None: |
---|
38 | self.logger = logging.getLogger(self.logger_name) |
---|
39 | if setup_console_handler: |
---|
40 | console = logging.StreamHandler() |
---|
41 | console.setLevel(logging.DEBUG) |
---|
42 | # We need to control the exact format: |
---|
43 | console.setFormatter(logging.Formatter('%(message)s')) |
---|
44 | self.logger.addHandler(console) |
---|
45 | self.logger.propagate = False |
---|
46 | if set_logger_level is not None: |
---|
47 | self.logger.setLevel(set_logger_level) |
---|
48 | else: |
---|
49 | self.logger = logger |
---|
50 | |
---|
51 | def __call__(self, environ, start_response): |
---|
52 | start = time.localtime() |
---|
53 | req_uri = urllib.quote(environ.get('SCRIPT_NAME', '') |
---|
54 | + environ.get('PATH_INFO', '')) |
---|
55 | if environ.get('QUERY_STRING'): |
---|
56 | req_uri += '?'+environ['QUERY_STRING'] |
---|
57 | def replacement_start_response(status, headers, exc_info=None): |
---|
58 | # @@: Ideally we would count the bytes going by if no |
---|
59 | # content-length header was provided; but that does add |
---|
60 | # some overhead, so at least for now we'll be lazy. |
---|
61 | bytes = None |
---|
62 | for name, value in headers: |
---|
63 | if name.lower() == 'content-length': |
---|
64 | bytes = value |
---|
65 | self.write_log(environ, req_uri, start, status, bytes) |
---|
66 | return start_response(status, headers) |
---|
67 | return self.application(environ, replacement_start_response) |
---|
68 | |
---|
69 | def write_log(self, environ, req_uri, start, status, bytes): |
---|
70 | if bytes is None: |
---|
71 | bytes = '-' |
---|
72 | if time.daylight: |
---|
73 | offset = time.altzone / 60 / 60 * -100 |
---|
74 | else: |
---|
75 | offset = time.timezone / 60 / 60 * -100 |
---|
76 | if offset >= 0: |
---|
77 | offset = "+%0.4d" % (offset) |
---|
78 | elif offset < 0: |
---|
79 | offset = "%0.4d" % (offset) |
---|
80 | d = { |
---|
81 | 'REMOTE_ADDR': environ.get('REMOTE_ADDR') or '-', |
---|
82 | 'REMOTE_USER': environ.get('REMOTE_USER') or '-', |
---|
83 | 'REQUEST_METHOD': environ['REQUEST_METHOD'], |
---|
84 | 'REQUEST_URI': req_uri, |
---|
85 | 'HTTP_VERSION': environ.get('SERVER_PROTOCOL'), |
---|
86 | 'time': time.strftime('%d/%b/%Y:%H:%M:%S ', start) + offset, |
---|
87 | 'status': status.split(None, 1)[0], |
---|
88 | 'bytes': bytes, |
---|
89 | 'HTTP_REFERER': environ.get('HTTP_REFERER', '-'), |
---|
90 | 'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'), |
---|
91 | } |
---|
92 | message = self.format % d |
---|
93 | self.logger.log(self.logging_level, message) |
---|
94 | |
---|
95 | def make_filter( |
---|
96 | app, global_conf, |
---|
97 | logger_name='wsgi', |
---|
98 | format=None, |
---|
99 | logging_level=logging.INFO, |
---|
100 | setup_console_handler=True, |
---|
101 | set_logger_level=logging.DEBUG): |
---|
102 | from paste.util.converters import asbool |
---|
103 | if isinstance(logging_level, basestring): |
---|
104 | logging_level = logging._levelNames[logging_level] |
---|
105 | if isinstance(set_logger_level, basestring): |
---|
106 | set_logger_level = logging._levelNames[set_logger_level] |
---|
107 | return TransLogger( |
---|
108 | app, |
---|
109 | format=format or None, |
---|
110 | logging_level=logging_level, |
---|
111 | logger_name=logger_name, |
---|
112 | setup_console_handler=asbool(setup_console_handler), |
---|
113 | set_logger_level=set_logger_level) |
---|
114 | |
---|
115 | make_filter.__doc__ = TransLogger.__doc__ |
---|