Change Flask Logging Output Format/Handler

April 25, 2019
import sys
import logging
from flask import Flask

app = Flask(__name__)

log = app.logger
formatter = logging.Formatter(fmt="%(asctime)s %(levelname)s %(module)s: %(message)s",
                          datefmt="%H:%M:%S")
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

# if this is not called, log will output both original and new format
log.handlers.clear()
log.addHandler(handler)


@app.route('/')
def test_logging():
    app.logger.info('app.logger')

    return 'Test logging'


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8088, debug=True)

New Logging Format

11:04:49 INFO test: app.logger

Original Flask Logging Format

[2019-04-25 11:09:27,943] INFO in test: app.logger
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.