Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Changeset 1285

Show
Ignore:
Timestamp:
08/26/06 17:54:36
Author:
fumanchu
Message:

Logging cleanups:

  1. Moved LogManager? to new _cplogging module.
  2. Apps now possess a 'log' attribute (a LogManager? instance that includes both error and access) instead of separate error_log and access_log.
  3. Fixed broken default error_log.
Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/cherrypy/__init__.py

    r1281 r1285  
    33__version__ = '3.0.0alpha' 
    44 
    5 import logging as _logging 
    65import os as _os 
    76_localdir = _os.path.dirname(__file__) 
     
    9493 
    9594 
     95from cherrypy import _cplogging 
    9696 
    97 #                                 Logging                                 # 
     97class _GlobalLogManager(_cplogging.LogManager): 
     98     
     99    def __call__(self, *args, **kwargs): 
     100        try: 
     101            log = request.app.log 
     102        except AttributeError: 
     103            log = self 
     104        return log.error(*args, **kwargs) 
     105     
     106    def access(self): 
     107        try: 
     108            return request.app.log.access() 
     109        except AttributeError: 
     110            return _cplogging.LogManager.access(self) 
    98111 
    99112 
    100 _error_log = _logging.getLogger("cherrypy.error") 
    101 _error_log.setLevel(_logging.DEBUG) 
    102 _access_log = _logging.getLogger("cherrypy.access") 
    103 _access_log.setLevel(_logging.INFO) 
    104  
    105  
    106 class _LogManager(object): 
    107      
    108     screen = True 
    109     error_file = _os.path.join(_os.getcwd(), _localdir, "error.log") 
    110     # Using an access file makes CP about 10% slower. 
    111     access_file = '' 
    112      
    113     def error(self, msg='', context='', severity=_logging.DEBUG, traceback=False): 
    114         """Write to the 'error' log. 
    115          
    116         This is not just for errors! Applications may call this at any time 
    117         to log application-specific information. 
    118         """ 
    119         if traceback: 
    120             from cherrypy import _cperror 
    121             msg += _cperror.format_exc() 
    122          
    123         try: 
    124             elog = request.app.error_log 
    125         except AttributeError: 
    126             elog = _error_log 
    127         elog.log(severity, ' '.join((self.time(), context, msg))) 
    128      
    129     def __call__(self, *args, **kwargs): 
    130         return self.error(*args, **kwargs) 
    131      
    132     def access(self): 
    133         """Write to the access log.""" 
    134         tmpl = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' 
    135         s = tmpl % {'h': request.remote.name or request.remote.ip, 
    136                     'l': '-', 
    137                     'u': getattr(request, "login", None) or "-", 
    138                     't': self.time(), 
    139                     'r': request.request_line, 
    140                     's': response.status.split(" ", 1)[0], 
    141                     'b': response.headers.get('Content-Length', '') or "-", 
    142                     'f': request.headers.get('referer', ''), 
    143                     'a': request.headers.get('user-agent', ''), 
    144                     } 
    145         try: 
    146             request.app.access_log.log(_logging.INFO, s) 
    147         except: 
    148             self.error(traceback=True) 
    149      
    150     def time(self): 
    151         """Return now() in Apache Common Log Format (no timezone).""" 
    152         import datetime, rfc822 
    153         now = datetime.datetime.now() 
    154         month = rfc822._monthnames[now.month - 1].capitalize() 
    155         return ('[%02d/%s/%04d:%02d:%02d:%02d]' % 
    156                 (now.day, month, now.year, now.hour, now.minute, now.second)) 
    157  
    158  
    159 log = _LogManager() 
     113log = _GlobalLogManager() 
     114log.error_file = _os.path.join(_os.getcwd(), _localdir, "error.log") 
     115# Using an access file makes CP about 10% slower. Leave off by default. 
     116log.access_file = '' 
    160117 
    161118 
  • trunk/cherrypy/_cpconfig.py

    r1281 r1285  
    7878 
    7979import ConfigParser 
    80 import logging as _logging 
    81 _logfmt = _logging.Formatter("%(message)s") 
    82 import os as _os 
    83 import types 
    84  
    8580import cherrypy 
    8681 
     
    162157        for k, v in conf.iteritems(): 
    163158            self[k] = v 
    164          
    165         _configure_builtin_logging(self, cherrypy._error_log) 
    166         _configure_builtin_logging(self, cherrypy._access_log, "log.access_file") 
    167159     
    168160    def __setitem__(self, k, v): 
     
    188180        return wrapper 
    189181    wrap = staticmethod(wrap) 
    190  
    191  
    192 def _add_builtin_screen_handler(log): 
    193     import sys 
    194     h = _logging.StreamHandler(sys.stdout) 
    195     h.setLevel(_logging.DEBUG) 
    196     h.setFormatter(_logfmt) 
    197     h._cpbuiltin = "screen" 
    198     log.addHandler(h) 
    199  
    200 def _add_builtin_file_handler(log, fname): 
    201     h = _logging.FileHandler(fname) 
    202     h.setLevel(_logging.DEBUG) 
    203     h.setFormatter(_logfmt) 
    204     h._cpbuiltin = "file" 
    205     log.addHandler(h) 
    206  
    207 def _configure_builtin_logging(conf, log, filekey="log.error_file"): 
    208     """Create/destroy builtin log handlers as needed from conf.""" 
    209      
    210     existing = dict([(getattr(x, "_cpbuiltin", None), x) 
    211                      for x in log.handlers]) 
    212     h = existing.get("screen") 
    213     screen = conf.get('log.screen') 
    214     if screen: 
    215         if not h: 
    216             _add_builtin_screen_handler(log) 
    217     elif h: 
    218         log.handlers.remove(h) 
    219      
    220     h = existing.get("file") 
    221     fname = conf.get(filekey) 
    222     if fname: 
    223         if h: 
    224             if h.baseFilename != _os.path.abspath(fname): 
    225                 h.close() 
    226                 log.handlers.remove(h) 
    227                 _add_builtin_file_handler(log, fname) 
    228         else: 
    229             _add_builtin_file_handler(log, fname) 
    230     else: 
    231         if h: 
    232             h.close() 
    233             log.handlers.remove(h) 
    234182 
    235183 
  • trunk/cherrypy/_cprequest.py

    r1281 r1285  
    433433            cherrypy.response.body = [] 
    434434         
    435         log_access = cherrypy.log.access 
    436         if log_access: 
    437             log_access() 
     435        cherrypy.log.access() 
    438436         
    439437        return cherrypy.response 
  • trunk/cherrypy/_cptree.py

    r1281 r1285  
    1 import logging 
    2  
    3 from cherrypy import _cpconfig, _cpwsgi 
     1from cherrypy import _cpconfig, _cplogging, _cpwsgi 
    42 
    53 
     
    2220     
    2321    def __init__(self, root, script_name="", conf=None): 
    24         self.access_log = log = logging.getLogger("cherrypy.access.%s" % id(self)) 
    25         log.setLevel(logging.INFO) 
    26          
    27         self.error_log = log = logging.getLogger("cherrypy.error.%s" % id(self)) 
    28         log.setLevel(logging.DEBUG) 
    29          
     22        self.log = _cplogging.LogManager(id(self)) 
    3023        self.root = root 
    3124        self.script_name = script_name 
     
    5043        # Create log handlers as specified in config. 
    5144        rootconf = self.conf.get("/", {}) 
    52         _cpconfig._configure_builtin_logging(rootconf, self.access_log, "log.access_file") 
    53         _cpconfig._configure_builtin_logging(rootconf, self.error_log) 
     45        for k, v in rootconf.iteritems(): 
     46            atoms = k.split(".", 1) 
     47            namespace = atoms[0] 
     48            if namespace == "log": 
     49                setattr(self.log, atoms[1], v) 
    5450     
    5551    def guess_abs_path(self): 

Hosted by WebFaction

Log in as guest/cpguest to create tickets