Python Tornado - disable logging to stderr

2019-03-26 14:15发布

问题:

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