Python Tornado - 禁用日志记录到stderr

时间:2014-01-20 12:57:04

标签: python tornado

我有简约的龙卷风应用程序:

import tornado.ioloop
import tornado.web

class PingHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("pong\n")

if __name__ == "__main__":
    application = tornado.web.Application([ ("/ping", PingHandler), ])
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Tornado不断向stderr报告错误请求:

WARNING:tornado.access:404 GET / (127.0.0.1) 0.79ms

问题:它希望阻止它记录错误消息。怎么样?

龙卷风3.1版; Python 2.6

3 个答案:

答案 0 :(得分:13)

很明显,当我们启动Tornado时,“某人”正在初始化日志记录子系统。以下是来自ioloop.py的代码,揭示了这个谜团:

def start(self):
    if not logging.getLogger().handlers:
        # The IOLoop catches and logs exceptions, so it's
        # important that log output be visible.  However, python's
        # default behavior for non-root loggers (prior to python
        # 3.2) is to print an unhelpful "no handlers could be
        # found" message rather than the actual log entry, so we
        # must explicitly configure logging if we've made it this
        # far without anything.
        logging.basicConfig()
调用

basicConfig并配置默认stderr处理程序。

因此,要为tonado访问设置正确的日志记录,您需要:

  1. tornado.access记录器添加处理程序:logging.getLogger("tornado.access").addHandler(...)

  2. 禁用上述记录器的传播:logging.getLogger("tornado.access").propagate = False。否则,消息将同时到达您的处理程序和stderr

答案 1 :(得分:11)

之前的回答是正确的,但有点不完整。这会将所有内容发送到NullHandler:

hn = logging.NullHandler()
hn.setLevel(logging.DEBUG)
logging.getLogger("tornado.access").addHandler(hn)
logging.getLogger("tornado.access").propagate = False

答案 2 :(得分:5)

你也可以很简单地(在一行中)做:

logging.getLogger('tornado.access').disabled = True
相关问题