Python Tornado - disable logging to stderr

◇◆丶佛笑我妖孽 提交于 2019-12-04 10:55:27

问题


I have minimalistic Tornado application:

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 keeps reporting error requests to stderr:

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

Question: It want to prevent it from logging error messages. How?

Tornado version 3.1; Python 2.6


回答1:


Its clear that "someone" is initializing logging subsystem when we start Tornado. Here is the code from ioloop.py that reveals the mystery:

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 is called and configures default stderr handler.

So to setup proper logging for tonado access, you need to:

  1. Add a handler to tornado.access logger: logging.getLogger("tornado.access").addHandler(...)

  2. Disable propagation for the above logger: logging.getLogger("tornado.access").propagate = False. Otherwise messages will arrive BOTH to your handler AND to stderr




回答2:


The previous answer was correct, but a little incomplete. This will send everything to the NullHandler:

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



回答3:


You could also quite simply (in one line) do:

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


来源:https://stackoverflow.com/questions/21234772/python-tornado-disable-logging-to-stderr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!