Ticket #13766: logging.patch

File logging.patch, 4.1 KB (added by djinn, 14 years ago)

logging patch for using python logging for output

  • django/core/servers/basehttp.py

     
    1414import stat
    1515import sys
    1616import urllib
     17import logging
    1718
    1819from django.core.management.color import color_style
    1920from django.utils.http import http_date
     
    2627sys_version = "Python/" + sys.version.split()[0]
    2728software_version = server_version + ' ' + sys_version
    2829
     30st_handler = logging.StreamHandler(sys.stderr)
     31formatter = logging.Formatter("[%(asctime)s] - %(levelname)s - %(message)s")
     32st_handler.setFormatter(formatter)
     33
     34log = logging.getLogger("WSGIServer")
     35log.addHandler(st_handler)
     36log.setLevel(logging.DEBUG)
     37admin_log = logging.getLogger("admin")
     38log.addHandler(st_handler)
     39log.setLevel(logging.DEBUG)
     40
    2941class WSGIServerException(Exception):
    3042    pass
    3143
     
    485497                exc_info[0], exc_info[1], exc_info[2],
    486498                self.traceback_limit, stderr
    487499            )
    488             stderr.flush()
     500
     501            log.warn(stderr.getvalue())
    489502        finally:
    490503            exc_info = None
    491504
     
    517530
    518531    def get_stderr(self):
    519532        return self.stderr
    520 
     533       
    521534    def add_cgi_vars(self):
    522535        self.environ.update(self.base_env)
    523536
     
    558571        # We set self.path to avoid crashes in log_message() on unsupported
    559572        # requests (like "OPTIONS").
    560573        self.path = ''
    561         self.style = color_style()
     574        #self.style = color_style()
    562575        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
    563576
    564577    def get_environ(self):
     
    595608        return env
    596609
    597610    def get_stderr(self):
    598         return sys.stderr
     611        from cStringIO import StringIO
     612        fake_stderr = StringIO()
     613        return fake_stderr
    599614
    600615    def handle(self):
    601616        """Handle a single HTTP request"""
    602617        self.raw_requestline = self.rfile.readline()
    603618        if not self.parse_request(): # An error code has been sent, just exit
    604619            return
    605         handler = ServerHandler(self.rfile, self.wfile, self.get_stderr(), self.get_environ())
     620        log_buffer = self.get_stderr()
     621        handler = ServerHandler(self.rfile, self.wfile, log_buffer, self.get_environ())
    606622        handler.request_handler = self      # backpointer for logging
    607623        handler.run(self.server.get_app())
    608 
     624        log_buffer.close()
     625       
    609626    def log_message(self, format, *args):
    610         # Don't bother logging requests for admin images or the favicon.
    611         if self.path.startswith(self.admin_media_prefix) or self.path == '/favicon.ico':
    612             return
     627        # Delay the decision of logging admin to logging config.
     628        if self.path.startswith(self.admin_media_prefix):
     629            int_logger = admin_log
     630        else:
     631            int_logger = log
     632       
     633        msg =  "%s\n" % (format % args)
    613634
    614         msg = "[%s] %s\n" % (self.log_date_time_string(), format % args)
    615 
    616         # Utilize terminal colors, if available
    617635        if args[1][0] == '2':
    618             # Put 2XX first, since it should be the common case
    619             msg = self.style.HTTP_SUCCESS(msg)
     636            int_logger.info(msg)
    620637        elif args[1][0] == '1':
    621             msg = self.style.HTTP_INFO(msg)
     638            int_logger.info(msg)
    622639        elif args[1] == '304':
    623             msg = self.style.HTTP_NOT_MODIFIED(msg)
     640            int_logger.info(msg)
    624641        elif args[1][0] == '3':
    625             msg = self.style.HTTP_REDIRECT(msg)
     642            int_logger.info(msg)
    626643        elif args[1] == '404':
    627             msg = self.style.HTTP_NOT_FOUND(msg)
     644            int_logger.warn(msg)
    628645        elif args[1][0] == '4':
    629             msg = self.style.HTTP_BAD_REQUEST(msg)
     646            int_logger.warn(msg)
    630647        else:
    631648            # Any 5XX, or any other response
    632             msg = self.style.HTTP_SERVER_ERROR(msg)
    633 
    634         sys.stderr.write(msg)
    635 
     649            int_logger.critical(msg)
     650           
     651       
    636652class AdminMediaHandler(object):
    637653    """
    638654    WSGI middleware that intercepts calls to the admin media directory, as
Back to Top