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

Changeset 1155

Show
Ignore:
Timestamp:
06/22/06 18:38:28
Author:
fumanchu
Message:

Fix for #256 (log file needs a lock). CherryPy now uses the stdlib's logging module. See the ticket for more details.

Files:

Legend:

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

    r1154 r1155  
    33__version__ = '3.0.0alpha' 
    44 
     5import logging 
    56 
    67from _cperror import HTTPError, HTTPRedirect, InternalRedirect, NotFound, WrongConfigValue 
     
    9192    return '%02d/%s/%04d:%02d:%02d:%02d' % ( 
    9293        now.day, month, now.year, now.hour, now.minute, now.second) 
     94 
     95_logfmt = logging.Formatter("%(message)s") 
     96 
     97_access_log = logging.getLogger("cherrypy.access") 
     98_access_log.setLevel(logging.INFO) 
     99 
     100def _add_access_log_handler(handler): 
     101    if handler.level == logging.NOTSET: 
     102        handler.setLevel(logging.INFO) 
     103    if handler.formatter is None: 
     104        handler.setFormatter(_logfmt) 
     105    _access_log.addHandler(handler) 
    93106 
    94107def log_access(): 
     
    105118                'a': request.headers.get('user-agent', ''), 
    106119                } 
    107      
    108     if config.get('log_to_screen', True): 
    109         print s 
    110      
    111     fname = config.get('log_access_file', '') 
    112     if fname: 
    113         f = open(fname, 'ab') 
    114         try: 
    115             f.write(s + '\n') 
    116         finally: 
    117             f.close() 
    118  
    119 _log_severity_levels = {0: "INFO", 1: "WARNING", 2: "ERROR"} 
    120  
    121 def _log_message(msg, context = '', severity = 0): 
     120         
     121    # Create handlers if needed 
     122    if not _access_log.handlers: 
     123        if config.get('server.log_to_screen'): 
     124            _add_access_log_handler(logging.StreamHandler(sys.stdout)) 
     125        fname = config.get('log_access_file', '') 
     126        if fname: 
     127            _add_access_log_handler(logging.FileHandler(fname)) 
     128     
     129    _access_log.log(logging.INFO, s) 
     130 
     131 
     132_error_log = logging.getLogger("cherrypy.error") 
     133_error_log.setLevel(logging.DEBUG) 
     134 
     135def _add_error_log_handler(handler): 
     136    if handler.level == logging.NOTSET: 
     137        handler.setLevel(logging.DEBUG) 
     138    if handler.formatter is None: 
     139        handler.setFormatter(_logfmt) 
     140    _error_log.addHandler(handler) 
     141 
     142def _log_message(msg, context = '', severity = logging.DEBUG): 
    122143    """Default method for logging messages (error log). 
    123144     
     
    126147    """ 
    127148     
    128     level = _log_severity_levels.get(severity, "UNKNOWN") 
    129      
    130     s = ' '.join((logtime(), context, level, msg)) 
    131      
    132     if config.get('log_to_screen', True): 
    133         print s 
    134      
    135     fname = config.get('log_file', '') 
    136     #logdir = os.path.dirname(fname) 
    137     #if logdir and not os.path.exists(logdir): 
    138     #    os.makedirs(logdir) 
    139     if fname: 
    140         f = open(fname, 'ab') 
    141         try: 
    142             f.write(s + '\n') 
    143         finally: 
    144             f.close() 
    145  
    146 def log(msg='', context='', severity=0, traceback=False): 
     149    # Create handlers if needed 
     150    if not _error_log.handlers: 
     151        if config.get('server.log_to_screen'): 
     152            _add_error_log_handler(logging.StreamHandler(sys.stdout)) 
     153        fname = config.get('log_file', '') 
     154        if fname: 
     155            _add_error_log_handler(logging.FileHandler(fname)) 
     156     
     157    _error_log.log(severity, ' '.join((logtime(), context, msg))) 
     158 
     159def log(msg='', context='', severity=logging.DEBUG, traceback=False): 
    147160    """Syntactic sugar for writing to the (error) log. 
    148161     
  • trunk/cherrypy/test/test_core.py

    r1145 r1155  
    1111import os 
    1212localDir = os.path.dirname(__file__) 
    13 log_file = os.path.join(localDir, "error.log") 
     13log_file = os.path.join(localDir, "test.log") 
    1414log_access_file = os.path.join(localDir, "access.log") 
    1515favicon_path = os.path.join(os.getcwd(), localDir, "../favicon.ico") 
     
    6868    class Params(Test): 
    6969         
    70         _cp_config = {'log_file': log_file} 
    71          
    7270        def index(self, thing): 
    7371            return repr(thing) 
     
    182180    class Flatten(Test): 
    183181         
    184         _cp_config = {'log_file': log_file, 
    185                       'log_access_file': log_access_file, 
    186                       } 
    187          
    188182        def as_string(self): 
    189183            return "content" 
     
    205199    class Error(Test): 
    206200         
    207         _cp_config = {'log_file': log_file, 
    208                       'tools.log_tracebacks.on': True, 
     201        _cp_config = {'tools.log_tracebacks.on': True, 
    209202                      } 
    210203         
     
    368361    cherrypy.config.update({ 
    369362        'log_to_screen': False, 
     363        'log_access_file': log_access_file, 
    370364        'server.protocol_version': "HTTP/1.1", 
    371365        'environment': 'production', 
     
    374368        'server.max_request_header_size': 500, 
    375369        }) 
     370    # When run via test.py, the engine is started (and the loggers created) 
     371    # before the above config.update, so we do it again manually. 
     372    import logging 
     373    cherrypy._add_error_log_handler(logging.FileHandler(log_file)) 
     374     
    376375    cherrypy.tree.mount(root) 
    377376 
     
    437436     
    438437    def testLogging(self): 
    439         open(log_file, "wb").write("") 
    440         open(log_access_file, "wb").write("") 
     438        f = open(log_access_file, "wb") 
     439        f.write("") 
     440        f.close() 
     441        f = open(log_file, "wb") 
     442        f.write("") 
     443        f.close() 
    441444         
    442445        self.getPage("/flatten/as_string") 
     
    454457            if k.lower() == 'content-length': 
    455458                haslength = True 
     459        line = data[-2].strip() 
    456460        if haslength: 
    457             self.assert_(data[0].endswith('] "GET %s/flatten/as_string HTTP/1.1" 200 7 "" ""\n
     461            self.assert_(line.endswith('] "GET %s/flatten/as_string HTTP/1.1" 200 7 "" ""
    458462                                          % self.prefix())) 
    459463        else: 
    460             self.assert_(data[0].endswith('] "GET %s/flatten/as_string HTTP/1.1" 200 - "" ""\n
     464            self.assert_(line.endswith('] "GET %s/flatten/as_string HTTP/1.1" 200 - "" ""
    461465                                          % self.prefix())) 
    462466         
    463         self.assertEqual(data[1][:15], '127.0.0.1 - - [') 
     467        self.assertEqual(data[-1][:15], '127.0.0.1 - - [') 
    464468        haslength = False 
    465469        for k, v in self.headers: 
    466470            if k.lower() == 'content-length': 
    467471                haslength = True 
     472        line = data[-1].strip() 
    468473        if haslength: 
    469             self.assert_(data[1].endswith('] "GET %s/flatten/as_yield HTTP/1.1" 200 7 "" ""\n
     474            self.assert_(line.endswith('] "GET %s/flatten/as_yield HTTP/1.1" 200 7 "" ""
    470475                                          % self.prefix())) 
    471476        else: 
    472             self.assert_(data[1].endswith('] "GET %s/flatten/as_yield HTTP/1.1" 200 - "" ""\n
     477            self.assert_(line.endswith('] "GET %s/flatten/as_yield HTTP/1.1" 200 - "" ""
    473478                                          % self.prefix())) 
    474          
    475         data = open(log_file, "rb").readlines() 
    476         self.assertEqual(data, []) 
    477479         
    478480        ignore = helper.webtest.ignored_exceptions 
     
    483485            self.assertInBody("raise ValueError()") 
    484486            data = open(log_file, "rb").readlines() 
    485             self.assertEqual(data[0][-41:], ' INFO Traceback (most recent call last):\n'
    486             self.assertEqual(data[-3], '    raise ValueError()\n'
     487            self.assertEqual(data[0].strip().endswith('HTTP Traceback (most recent call last):'), True
     488            self.assertEqual(data[-3].strip().endswith('raise ValueError()'), True
    487489        finally: 
    488490            ignore.pop() 

Hosted by WebFaction

Log in as guest/cpguest to create tickets