有没有办法让Bottle服务器更简洁?

时间:2012-07-28 02:10:58

标签: python bottle

是否有任何选项在瓶子上可以让 WSGIRef 粘贴等服务器为每个收到的请求输出一行?< / p>

NB:我知道有一个安静的选项,但我不希望整个应用程序保持沉默,只需要请求日志。

它很快就会变得非常混乱,特别是考虑到我想要时不时地打印调试信息,它就会在混乱中迷失。这是单页加载的输出,当项目增长时,它可能会变得更大:

Bottle server starting up (using WSGIRefServer())...
Listening on http://0.0.0.0:8080/
Hit Ctrl-C to quit.

localhost - - [28/Jul/2012 04:05:59] "GET /clients HTTP/1.1" 200 3129
localhost - - [28/Jul/2012 04:05:59] "GET /static/css/main.css HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery-1.7.2.js HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery.cookie.js HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery.qtip.min.js HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/js/showdown.js HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/js/proj.js HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:05:59] "GET /static/css/reset.css HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:06:00] "GET /static/images/flag_gb.png HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:06:00] "GET /static/images/flag_no.png HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:06:00] "GET /static/images/icon_add.png HTTP/1.1" 304 0
localhost - - [28/Jul/2012 04:06:00] "GET /favicon.ico HTTP/1.1" 404 742

1 个答案:

答案 0 :(得分:1)

我过去做过类似的事情。对于不同类型的服务器,您可以覆盖日志处理程序以过滤掉您不想要的日志。我从Bottle复制代码并创建自己的ServerAdapter,下面是WSGI服务器的代码。类似于安静的功能覆盖log_request函数我自己的处理程序类并覆盖原始的log_request,然后根据传递给函数的响应代码过滤掉消息。

我从内置的BaseHTTPServer模块复制了log_request函数,并添加了if语句。

然后当您启动瓶子时,将其传递给您的客户服务器适配器

from bottle import route, run, template
import bottle

@route('/hello/:name')
def index(name='World'):
    print "Debug Print Statement"
    return template('<b>Hello {{name}}</b>!', name=name)

class WSGIRefServer(bottle.ServerAdapter):
    def run(self, handler): # pragma: no cover
        from wsgiref.simple_server import make_server, WSGIRequestHandler

        class LogHandler(WSGIRequestHandler):
            def log_request(self, code='-', size='-'):
                """Log an accepted request.

                This is called by send_response().

                """
                if code not in  ["200", "304"]:
                    self.log_message('"%s" %s %s',
                                     self.requestline, str(code), str(size))

        self.options['handler_class'] = LogHandler
        srv = make_server(self.host, self.port, handler, **self.options)
        srv.serve_forever()


run(host='localhost', server=WSGIRefServer, port=8080)