source: publico/il.spdo/trunk/Paste-1.7.5.1-py2.6.egg/paste/translogger.py @ 5327

Última Alteração nesse arquivo desde 5327 foi 5327, incluída por fabianosantos, 8 anos atrás

Import inicial.

File size: 4.7 KB
Linha 
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)
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        remote_addr = '-'
82        if environ.get('HTTP_X_FORWARDED_FOR'):
83            remote_addr = environ['HTTP_X_FORWARDED_FOR']
84        elif environ.get('REMOTE_ADDR'):
85            remote_addr = environ['REMOTE_ADDR']
86        d = {
87            'REMOTE_ADDR': remote_addr,
88            'REMOTE_USER': environ.get('REMOTE_USER') or '-',
89            'REQUEST_METHOD': method,
90            'REQUEST_URI': req_uri,
91            'HTTP_VERSION': environ.get('SERVER_PROTOCOL'),
92            'time': time.strftime('%d/%b/%Y:%H:%M:%S ', start) + offset,
93            'status': status.split(None, 1)[0],
94            'bytes': bytes,
95            'HTTP_REFERER': environ.get('HTTP_REFERER', '-'),
96            'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'),
97            }
98        message = self.format % d
99        self.logger.log(self.logging_level, message)
100
101def make_filter(
102    app, global_conf,
103    logger_name='wsgi',
104    format=None,
105    logging_level=logging.INFO,
106    setup_console_handler=True,
107    set_logger_level=logging.DEBUG):
108    from paste.util.converters import asbool
109    if isinstance(logging_level, basestring):
110        logging_level = logging._levelNames[logging_level]
111    if isinstance(set_logger_level, basestring):
112        set_logger_level = logging._levelNames[set_logger_level]
113    return TransLogger(
114        app,
115        format=format or None,
116        logging_level=logging_level,
117        logger_name=logger_name,
118        setup_console_handler=asbool(setup_console_handler),
119        set_logger_level=set_logger_level)
120
121make_filter.__doc__ = TransLogger.__doc__
Note: Veja TracBrowser para ajuda no uso do navegador do trac.
 

The contents and data of this website are published under license:
Creative Commons 4.0 Brasil - Atribuir Fonte - Compartilhar Igual.