public
Last active — forked from dAnjou/server.py

Flask logging example

  • Download Gist
foo.log
1 2
A warning occurred (42 apples)
An error occurred
server.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import logging
from logging.handlers import RotatingFileHandler
 
from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def foo():
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')
app.logger.info('Info')
return "foo"
 
if __name__ == '__main__':
handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
app.run()

Thanks for the tip

Lovely my friend! Thanks a lot for putting up this code chunk!

Thanks its very useful :) Does flask provides a default logger or we have to provide one for it like RotatingFileHandler?

You can add this:

handler.setLevel(logging.ERROR)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

to include time and other info in the log item.

If you want line numbers as well in your logs, you can use this formatter:

    formatter = logging.Formatter(
        "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
    handler = RotatingFileHandler(LOG_FILENAME, maxBytes=10000000, backupCount=5)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

If you also want to see the log messages emitted by Werkzeug in your log file, you can add the following:

    log = logging.getLogger('werkzeug')
    log.setLevel(logging.DEBUG)
    log.addHandler(handler)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.