Search code examples
pythonloggingflasktornado

how to manage multiple loggers in python flask-tornado application


I'm building a python application with also a web interface, with Flask web framework. It runs on Flask internal server in debug/dev mode and in production mode it runs on tornado as wsgi container. This is how i've set up my logger:

log_formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')

file_handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=5 * 1024 * 1024, backupCount=10)
file_handler.setFormatter(log_formatter)

console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_formatter)

log = logging.getLogger('myAppLogger')
log.addHandler(file_handler)
log.addHandler(console_handler)

To add my logger to the Flask app i tried this:

app = Flask('system.web.server')
app.logger_name = 'myAppLogger'

But the log still going to the Flask default log handler, and in addition, I didn't found how to customize the log handlers also for the Tornado web server. Any help is much appreciated, thanks in advance


Solution

  • AFAIK, you can't change the default logger in Flask. You can, however, add your handlers to the default logger:

    app = Flask('system.web.server')
    app.logger.addHandler(file_handler)
    app.logger.addHandler(console_handler)
    

    Regarding my comment above - "Why would you want to run Flask in tornado ...", ignore that. If you are not seeing any performance hit, then clearly there's no need to change your setup.

    If, however, in future you'd like to migrate to a multithreaded container, you can look into uwsgi or gunicorn.