控制wsgiref simple_server日志

时间:2015-07-15 14:47:53

标签: python python-2.7 wsgiref

我正在玩wsgiref.simple_server来研究网络服务器的世界。
我想控制生成的日志,但在Python's documentation中找不到任何相关内容。

我的代码如下所示:

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()

2 个答案:

答案 0 :(得分:16)

wsgiref.simple_server.make_server默认情况下使用WSGIServer创建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此处从BaseHTTPServer.BaseHTTPRequestHandler延伸,其中记录魔法证明是:

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

所以,它实际上是登录到stderr,而不是python日志记录模块。您可以在自己的处理程序中覆盖它:

class NoLoggingWSGIRequestHandler(WSGIRequestHandler):

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

将您的自定义处理程序传递给服务器:

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

答案 1 :(得分:0)

另一个奇怪的技巧是使用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()