Flask Development Logging

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

app = Flask(__name__)

app.logger.setLevel(logging.DEBUG)
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger().setLevel(logging.DEBUG)

# create a local module logger
log = logging.getLogger(__name__)
if not log.handlers:
    log.setLevel(logging.DEBUG)
    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)

    # log.propagate = False
    log.addHandler(handler)

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

    print('print')

    # same as app.logger
    logging.getLogger('flask.app').info('flask.app')

    log.info('module log')

    return 'Test logging'

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

Output

[2019-04-25 11:29:17,796] INFO in test: app.logger
print
[2019-04-25 11:29:17,797] INFO in test: flask.app
11:29:17 INFO test: module log
127.0.0.1 - - [25/Apr/2019 11:29:17] "GET / HTTP/1.1" 200 -

NOTE: Refer to Change Flask Logging Output Format/Handler

NOTE: Refer to Flask Logging Appear Twice

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.