search by tags

for the user

adventures into the land of the command line

flask & gunicorn combined logging

this is based on this groovy post i found online about combining the flask and gunicorn loggers into one log. the only difference is that this works also for flask blueprints.

in your main application file you can set up your logging like this to use the gunicorn logger as the location for where the flask app logger should write to.

import logging

if __name__ != '__main__':
    my_groovy_logger = logging.getLogger('my_groovy_app.main')
    logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S %z')
    app.logger.handlers = my_groovy_logger.handlers

from views import *

if __name__ == '__main__':

and in your views, just use the default logging like so

import logging

@views.route('/v1/some_view', methods=['POST'])
def some_view():
    logging.error('my_groovy_app.some_view: Some groovy log message.')

start gunicorn with the log-level option

gunicorn -w 1 -k eventlet -b --log-level=info -t 60 main:app

and the flask logs will go to the same file as the gunicorn logs

[2019-03-23 19:19:07 +0000] [7138] [INFO] Starting gunicorn 19.3.0
[2019-03-23 19:19:07 +0000] [7138] [INFO] Listening at: (7138)
[2019-03-23 19:19:07 +0000] [7138] [INFO] Using worker: eventlet
[2019-03-23 19:19:07 +0000] [7146] [INFO] Booting worker with pid: 7146

[2019-03-23 19:19:17 +0000] [root] [ERROR] my_groovy_app.some_view: Some groovy log message.

[2019-03-23 19:01:48 +0000] [7146] [ERROR] Error handling request
Traceback (most recent call last):
ValueError: malformed string