Python Tornado-禁用到std的日志记录

2024-09-22 14:19:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

Tornado版本3.1;Python2.6


Tags: importselfweb应用程序getapplicationdef错误
3条回答

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

logging.getLogger('tornado.access').disabled = True

前面的答案是正确的,但有点不完整。这将把所有内容发送给NullHandler:

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

很明显,当我们启动龙卷风时,“有人”正在初始化日志子系统。以下是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

相关问题 更多 >