Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@maxcnunes

maxcnunes Jan 6, 2013

Thanks for the tip

Thanks for the tip

@tabdulradi

This comment has been minimized.

Show comment
Hide comment
@tabdulradi

tabdulradi Mar 13, 2013

Thanks dude

Thanks dude

@cruisemaniac

This comment has been minimized.

Show comment
Hide comment
@cruisemaniac

cruisemaniac Apr 24, 2013

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

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

@webus

This comment has been minimized.

Show comment
Hide comment

webus commented May 11, 2013

Thanks!

@umurgdk

This comment has been minimized.

Show comment
Hide comment
@umurgdk

umurgdk Aug 18, 2013

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

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

This comment has been minimized.

Show comment
Hide comment
@vkotovv

vkotovv 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.

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

This comment has been minimized.

Show comment
Hide comment
@rkrzr

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

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

This comment has been minimized.

Show comment
Hide comment

thanks :)

@joshgeller

This comment has been minimized.

Show comment
Hide comment

Thank you

@kirankoduru

This comment has been minimized.

Show comment
Hide comment

Thanks !

@Prawyn

This comment has been minimized.

Show comment
Hide comment

Prawyn commented Jun 13, 2014

Thanks

@icron

This comment has been minimized.

Show comment
Hide comment

icron commented Dec 27, 2014

Thanks

@ElMijo

This comment has been minimized.

Show comment
Hide comment
@ElMijo

ElMijo Jan 7, 2015

Muchas gracias..

ElMijo commented Jan 7, 2015

Muchas gracias..

@KCzar

This comment has been minimized.

Show comment
Hide comment
@KCzar

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

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

This comment has been minimized.

Show comment
Hide comment
@bloodynumen

bloodynumen Mar 17, 2015

Thx~ It help me

Thx~ It help me

@biratrai

This comment has been minimized.

Show comment
Hide comment
@biratrai

biratrai Mar 25, 2015

Where will be the .log files be saved??

Where will be the .log files be saved??

@louking

This comment has been minimized.

Show comment
Hide comment
@louking

louking 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.

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

This comment has been minimized.

Show comment
Hide comment
@swordfly

swordfly Mar 30, 2015

It's very useful, thank you!

It's very useful, thank you!

@anish-mp

This comment has been minimized.

Show comment
Hide comment
@anish-mp

anish-mp Apr 15, 2015

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

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

This comment has been minimized.

Show comment
Hide comment
@andyxning

andyxning Apr 18, 2015

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

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

This comment has been minimized.

Show comment
Hide comment

Schlik commented May 22, 2015

Thanks!

@wujiwh

This comment has been minimized.

Show comment
Hide comment
@wujiwh

wujiwh Jul 15, 2015

cool !!! very useful, Thx~

wujiwh commented Jul 15, 2015

cool !!! very useful, Thx~

@swdream

This comment has been minimized.

Show comment
Hide comment
@swdream

swdream 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.

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

This comment has been minimized.

Show comment
Hide comment
@adityak2190

adityak2190 Jul 22, 2015

From the example in the beginning try this -

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

From the example in the beginning try this -

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

@harishkashyap

This comment has been minimized.

Show comment
Hide comment
@harishkashyap

harishkashyap Sep 30, 2015

great! thanks for this nice little snippet that works

great! thanks for this nice little snippet that works

@vi3k6i5

This comment has been minimized.

Show comment
Hide comment
@vi3k6i5

vi3k6i5 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?

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

This comment has been minimized.

Show comment
Hide comment
@ringxw

ringxw Nov 4, 2015

Thank you to both @ibeex and @rkrzr !

ringxw commented Nov 4, 2015

Thank you to both @ibeex and @rkrzr !

@Marabou

This comment has been minimized.

Show comment
Hide comment
@Marabou

Marabou Nov 6, 2015

Great!! :)

Marabou commented Nov 6, 2015

Great!! :)

@rlam3

This comment has been minimized.

Show comment
Hide comment
@rlam3

rlam3 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

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

This comment has been minimized.

Show comment
Hide comment

Thanks

@weaming

This comment has been minimized.

Show comment
Hide comment

weaming commented Nov 27, 2015

THX

@zws2lll

This comment has been minimized.

Show comment
Hide comment

zws2lll commented Jan 28, 2016

thanks

@dynastysea

This comment has been minimized.

Show comment
Hide comment
@dynastysea

dynastysea Feb 5, 2016

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

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

@unlessbamboo

This comment has been minimized.

Show comment
Hide comment

Thanks.

@Tallone

This comment has been minimized.

Show comment
Hide comment
@Tallone

Tallone May 24, 2016

i finally could not use print ~~

Tallone commented May 24, 2016

i finally could not use print ~~

@tOlorun

This comment has been minimized.

Show comment
Hide comment
@tOlorun

tOlorun Jul 8, 2016

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) handler.setLevel(logging.DEBUG) formatter = logging.Formatter( "[%(asctime)s] {%(pathname)s:%(lineno)d} | %(funcName)s | %(levelname)s - %(message)s") handler.setFormatter(formatter) loga = logging.getLogger('werkzeug') loga.setLevel(logging.DEBUG) loga.addHandler(handler) app.logger.addHandler(handler)

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

tOlorun commented Jul 8, 2016

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) handler.setLevel(logging.DEBUG) formatter = logging.Formatter( "[%(asctime)s] {%(pathname)s:%(lineno)d} | %(funcName)s | %(levelname)s - %(message)s") handler.setFormatter(formatter) loga = logging.getLogger('werkzeug') loga.setLevel(logging.DEBUG) loga.addHandler(handler) app.logger.addHandler(handler)

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

@imdanielsp

This comment has been minimized.

Show comment
Hide comment
@imdanielsp

imdanielsp Aug 27, 2016

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

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

@ranvijay-sachan

This comment has been minimized.

Show comment
Hide comment
@zfrenchee

This comment has been minimized.

Show comment
Hide comment
@zfrenchee

zfrenchee Jan 23, 2017

This gist seems to print 4 lines for every call to log, e.g.

--------------------------------------------------------------------------------
INFO in app [/usr/src/app/app.py:187]:
successful query
--------------------------------------------------------------------------------

How do you get it to print on just one line? http://stackoverflow.com/questions/41783774/how-to-log-in-flask

This gist seems to print 4 lines for every call to log, e.g.

--------------------------------------------------------------------------------
INFO in app [/usr/src/app/app.py:187]:
successful query
--------------------------------------------------------------------------------

How do you get it to print on just one line? http://stackoverflow.com/questions/41783774/how-to-log-in-flask

@sanfx

This comment has been minimized.

Show comment
Hide comment
@sanfx

sanfx Sep 5, 2017

Hi All,

I am using logging in various python apps, your post logging for flask speciically was helpful, however is there a web based log viewer, that I can just login and view logs if any generated by my app ?

sanfx commented Sep 5, 2017

Hi All,

I am using logging in various python apps, your post logging for flask speciically was helpful, however is there a web based log viewer, that I can just login and view logs if any generated by my app ?

@oakbani

This comment has been minimized.

Show comment
Hide comment
@oakbani

oakbani Nov 30, 2017

Thanks a lot

oakbani commented Nov 30, 2017

Thanks a lot

@bickyeric

This comment has been minimized.

Show comment
Hide comment

Thanks.

@narakus

This comment has been minimized.

Show comment
Hide comment

narakus commented Jan 19, 2018

Thinks

@sergejschelle

This comment has been minimized.

Show comment
Hide comment
@sergejschelle

sergejschelle Jan 24, 2018

Very useful, thank you! Some other logging handlers are here: https://docs.python.org/2/library/logging.handlers.html

Very useful, thank you! Some other logging handlers are here: https://docs.python.org/2/library/logging.handlers.html

@lindseymenges

This comment has been minimized.

Show comment
Hide comment
@lindseymenges

lindseymenges Mar 27, 2018

Very helpful, thank you!

Very helpful, thank you!

@asmaier

This comment has been minimized.

Show comment
Hide comment
@asmaier

asmaier Apr 17, 2018

Thank you for this gist. In addition if you only want to log to stdout do the following:

import sys
import logging
import flask

app = flask.Flask(__name__)

@app.before_first_request
def setup_logging():
    if not app.debug:
        # In production mode, add log handler to sys.stdout.
        app.logger.addHandler(logging.StreamHandler(stream=sys.stdout))
        app.logger.setLevel(logging.INFO)

This is necessary, because Flask does not log messages in production mode by default. To get Flask's app.logger to log messages, you'll always have to add a logging handler, even for simply logging to stdout.

see

asmaier commented Apr 17, 2018

Thank you for this gist. In addition if you only want to log to stdout do the following:

import sys
import logging
import flask

app = flask.Flask(__name__)

@app.before_first_request
def setup_logging():
    if not app.debug:
        # In production mode, add log handler to sys.stdout.
        app.logger.addHandler(logging.StreamHandler(stream=sys.stdout))
        app.logger.setLevel(logging.INFO)

This is necessary, because Flask does not log messages in production mode by default. To get Flask's app.logger to log messages, you'll always have to add a logging handler, even for simply logging to stdout.

see

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