Why is Flask application not creating any logs when hosted by Gunicorn?

后端 未结 3 724
独厮守ぢ
独厮守ぢ 2020-12-24 02:00

I\'m trying to add logging to a web application which uses Flask.

When hosted using the built-in server (i.e. python3 server.py), logging works. When ho

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 02:32

    There are a couple of reasons behind this: Gunicorn has its own loggers, and it’s controlling log level through that mechanism. A fix for this would be to add app.logger.setLevel(logging.DEBUG).
    But what’s the problem with this approach? Well, first off, that’s hard-coded into the application itself. Yes, we could refactor that out into an environment variable, but then we have two different log levels: one for the Flask application, but a totally separate one for Gunicorn, which is set through the --log-level parameter (values like “debug”, “info”, “warning”, “error”, and “critical”).

    A great solution to solve this problem is the following snippet:

    import logging
    from flask import Flask, jsonify
    
    app = Flask(__name__)
    
    @app.route('/')
    def default_route():
        """Default route"""
        app.logger.debug('this is a DEBUG message')
        app.logger.info('this is an INFO message')
        app.logger.warning('this is a WARNING message')
        app.logger.error('this is an ERROR message')
        app.logger.critical('this is a CRITICAL message')
        return jsonify('hello world')
    
    if __name__ == '__main__':
        app.run(host=0.0.0.0, port=8000, debug=True)
    
    else:
        gunicorn_logger = logging.getLogger('gunicorn.error')
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)
    

    Refrence: Code and Explanation is taken from here

提交回复
热议问题