Skip to content
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__)
@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()
@maxcnunes

Thanks for the tip

@tabdulradi

Thanks dude

@cruisemaniac

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

@webus
webus commented May 11, 2013

Thanks!

@umurgdk
umurgdk commented Aug 18, 2013

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

@vkotovv
vkotovv commented Sep 20, 2013

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.

@rkrzr
rkrzr commented Nov 8, 2013

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)
@Sethathi

thanks :)

@joshgeller

Thank you

@kirankoduru

Thanks !

@Prawyn
Prawyn commented Jun 13, 2014

Thanks

@icron
icron commented Dec 27, 2014

Thanks

@ElMijo
ElMijo commented Jan 7, 2015

Muchas gracias..

@KCzar
KCzar commented Feb 20, 2015

I had to setLevel on app.logger as well to make it log from app.logger.info("...") 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)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)
@bloodynumen

Thx~ It help me

@biratrai

Where will be the .log files be saved??

@louking
louking commented Mar 27, 2015

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.

@swordfly

It's very useful, thank you!

@anish-mp

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

@andyxning

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 logging.py file you will find what the problem is. Here is the link

@Schlik
Schlik commented May 22, 2015

Thanks!

@wujiwh
wujiwh commented Jul 15, 2015

cool !!! very useful, Thx~

@swdream
swdream commented Jul 21, 2015

When I follow above example:
handler = RotatingFileHandler(maxBytes=10000, backupCount=1)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)

I got below error:

Traceback (most recent call last):
File "main.py", 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.

@adityak2190

From the example in the beginning try this -

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

@harishkashyap

great! thanks for this nice little snippet that works

@vi3k6i5
vi3k6i5 commented Oct 15, 2015

How do i pass it to the next file ??

say i have another file bar.py

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?

@ringxw
ringxw commented Nov 4, 2015

Thank you to both @ibeex and @rkrzr !

@Marabou
Marabou commented Nov 6, 2015

Great!! :)

@rlam3
rlam3 commented Nov 10, 2015

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

@HRKpython

Thanks

@weaming
weaming commented Nov 27, 2015

THX

@zws2lll
zws2lll commented Jan 28, 2016

thanks

@dynastysea

info log cannot be record, we should set
app.logger.setLevel(logging.INFO)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.