Skip to content
Advertisement

Control wsgiref simple_server log

I’m playing with wsgiref.simple_server to study the world of web servers.
I would like to control the log generated, but could not find anything about it in Python’s documentation.

My code looks like this:

from wsgiref.simple_server import make_server

def application(environ, start_response):
  start_response('200 OK', headers)
  return ['Hello World']

httpd = make_server('', 8000, application)
httpd.serve_forever()

Advertisement

Answer

wsgiref.simple_server.make_server by default creates a WSGIServer with WSGIRequestHandler:

def make_server(
    host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler):
    """Create a new WSGI server listening on `host` and `port` for `app`"""
    server = server_class((host, port), handler_class)
    server.set_app(app)
    return server

WSGIRequestHandler here extends from BaseHTTPServer.BaseHTTPRequestHandler, where the logging magic turns out to be:

def log_message(self, format, *args):
    sys.stderr.write("%s - - [%s] %sn" %
                     (self.client_address[0],
                      self.log_date_time_string(),
                      format%args))

So it’s logging to stderr, actually, not to python logging module. You can override this in your own handler:

class NoLoggingWSGIRequestHandler(WSGIRequestHandler):

    def log_message(self, format, *args):
        pass

And pass your custom handler to the server instead:

httpd = make_server('', 8000, application, handler_class=NoLoggingWSGIRequestHandler)
Advertisement