root/galaxy-central/lib/galaxy/web/framework/middleware/translogger.py @ 3

リビジョン 2, 4.5 KB (コミッタ: hatakeyama, 14 年 前)

import galaxy-central

行番号 
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"""
4Middleware for logging requests, using Apache combined log format
5"""
6
7import logging
8import time
9import urllib
10
11class 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        method = environ['REQUEST_METHOD']
58        def replacement_start_response(status, headers, exc_info=None):
59            # @@: Ideally we would count the bytes going by if no
60            # content-length header was provided; but that does add
61            # some overhead, so at least for now we'll be lazy.
62            bytes = None
63            for name, value in headers:
64                if name.lower() == 'content-length':
65                    bytes = value
66            self.write_log(environ, method, req_uri, start, status, bytes)
67            return start_response( status, headers, exc_info )
68        return self.application(environ, replacement_start_response)
69
70    def write_log(self, environ, method, req_uri, start, status, bytes):
71        if bytes is None:
72            bytes = '-'
73        if time.daylight:
74                offset = time.altzone / 60 / 60 * -100
75        else:
76                offset = time.timezone / 60 / 60 * -100
77        if offset >= 0:
78                offset = "+%0.4d" % (offset)
79        elif offset < 0:
80                offset = "%0.4d" % (offset)
81        d = {
82            'REMOTE_ADDR': environ.get('REMOTE_ADDR') or '-',
83            'REMOTE_USER': environ.get('REMOTE_USER') or '-',
84            'REQUEST_METHOD': method,
85            'REQUEST_URI': req_uri,
86            'HTTP_VERSION': environ.get('SERVER_PROTOCOL'),
87            'time': time.strftime('%d/%b/%Y:%H:%M:%S ', start) + offset,
88            'status': status.split(None, 1)[0],
89            'bytes': bytes,
90            'HTTP_REFERER': environ.get('HTTP_REFERER', '-'),
91            'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'),
92            }
93        message = self.format % d
94        self.logger.log(self.logging_level, message)
95
96def make_filter(
97    app, global_conf,
98    logger_name='wsgi',
99    format=None,
100    logging_level=logging.INFO,
101    setup_console_handler=True,
102    set_logger_level=logging.DEBUG):
103    from paste.util.converters import asbool
104    if isinstance(logging_level, basestring):
105        logging_level = logging._levelNames[logging_level]
106    if isinstance(set_logger_level, basestring):
107        set_logger_level = logging._levelNames[set_logger_level]
108    return TransLogger(
109        app,
110        format=format or None,
111        logging_level=logging_level,
112        logger_name=logger_name,
113        setup_console_handler=asbool(setup_console_handler),
114        set_logger_level=set_logger_level)
115
116make_filter.__doc__ = TransLogger.__doc__
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。