Create a gist now

Instantly share code, notes, and snippets.

Flask logging example
A warning occurred (42 apples)
An error occurred
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
app = Flask(__name__)
def foo():
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')'Info')
return "foo"
if __name__ == '__main__':
handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=1)

Thanks for the tip


Thanks dude


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:

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)

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')

thanks :)


Thank you


Thanks !






Muchas gracias..


I had to setLevel on app.logger as well to make it log from"...") and app.logger.debug("..."). If I only set the level of the handler, it would only log warn, error, and critical messages.

Here's what worked for me:

handler = TimedRotatingFileHandler('logs/foo.log', when='midnight', interval=1)

Thx~ It help me


Where will be the .log files be saved??


Thanks @KCzar -- I was having a devil of a time figuring out why my info messages were not being logged, setting level on app.logger fixed that problem.


It's very useful, thank you!


Thanks, useful code . It will be better if uniform field separator is used, this allows for log processing by automation tools . Eg
formatter = logging.Formatter(
"%(asctime)s | %(pathname)s:%(lineno)d |
%(funcName)s | %(levelname)s | %(message)s ")


the reason for set log level in app.logger in production is that app.logger set level of app.logger to logging.NOTSET(i.e. 0), and if app.debug is True then all log level above DEBUG will be logged to stderr(StreamHandler). However, if app.debuug is set to False then all the log level above logging.root.level(i.e. logging.WARNING). Check out the code about Flask file you will find what the problem is. Here is the link




cool !!! very useful, Thx~


When I follow above example:
handler = RotatingFileHandler(maxBytes=10000, backupCount=1)

I got below error:

Traceback (most recent call last):
File "", line 33, in
handler = RotatingFileHandler(maxBytes=10000, backupCount=1)
TypeError: init() takes at least 2 arguments (3 given)

Can you help me to explain about this? thank you very much.


From the example in the beginning try this -

handler = RotatingFileHandler('foo.log', maxBytes=10000, backupCount=1)


great! thanks for this nice little snippet that works


How do i pass it to the next file ??

say i have another file

and it has a method

def bar_method():
    print "in bar"

bar_method is called by foo.
I want to use same logging style here. how to do that?


Thank you to both @ibeex and @rkrzr !


Great!! :)


You have to set the handler to a level lower than the logger record or else it will not emit the message








info log cannot be record, we should set




i finally could not use print ~~


hello everyone

Please is it possible to put this in a function where you can pass the log file to when called

like so

def logga(log_file):
handler = TimedRotatingFileHandler('logs/%s.log' % log_file, when='midnight', interval=1)
formatter = logging.Formatter(
"[%(asctime)s] {%(pathname)s:%(lineno)d} | %(funcName)s | %(levelname)s - %(message)s")
loga = logging.getLogger('werkzeug')

The above does not currently work . ..
thanks in advance


Great and to the point, just what I needed. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment