11

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()
gibatronic
  • 1,661
  • 2
  • 17
  • 22

2 Answers2

25

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] %s\n" %
                     (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)
Tuukka Mustonen
  • 4,722
  • 9
  • 49
  • 79
-1

Another weird trick, is to use redirect_stderr.

import os
from contextlib import redirect_stderr


with redirect_stderr(open(os.devnull, "w")):
    with make_server("", 8051, app) as httpd:
        httpd.handle_request()
Dev Aggarwal
  • 7,627
  • 3
  • 38
  • 50