Skip to content

Instantly share code, notes, and snippets.

@ibeex
Created August 4, 2012 13:46
Show Gist options
  • Save ibeex/3257877 to your computer and use it in GitHub Desktop.
Save ibeex/3257877 to your computer and use it in GitHub Desktop.
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()
@swdream
Copy link

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.

@adikrishnan
Copy link

From the example in the beginning try this -

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

@harishkashyap
Copy link

great! thanks for this nice little snippet that works

@vi3k6i5
Copy link

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
Copy link

ringxw commented Nov 4, 2015

Thank you to both @ibeex and @rkrzr !

@Marabou
Copy link

Marabou commented Nov 6, 2015

Great!! :)

@rlam3
Copy link

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
Copy link

Thanks

@weaming
Copy link

weaming commented Nov 27, 2015

THX

@zws2lll
Copy link

zws2lll commented Jan 28, 2016

thanks

@chaohi
Copy link

chaohi commented Feb 5, 2016

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

@unlessbamboo
Copy link

Thanks.

@Tallone
Copy link

Tallone commented May 24, 2016

i finally could not use print ~~

@tOlorun
Copy link

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
Copy link

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

@ranvijay-sachan
Copy link

@alexlenail
Copy link

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
Copy link

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
Copy link

oakbani commented Nov 30, 2017

Thanks a lot

@bickyeric
Copy link

Thanks.

@narakus
Copy link

narakus commented Jan 19, 2018

Thinks

@sergejschelle
Copy link

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

@lindseymenges
Copy link

Very helpful, thank you!

@asmaier
Copy link

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

@jkarstens
Copy link

It is not the case (at least anymore) that you'll always have to explicitly add a logging handler to get Flask's app.logger to log messages. According to http://flask.pocoo.org/docs/1.0/logging/, we can simply make a logging.basicConfig(...) call before creating the Flask app, like

import flask
import logging

logging.basicConfig(filename=LOG_FILENAME, format=LOG_FORMAT, level=LOG_LEVEL)

app = Flask(__name__)

This worked for me in a production environment on all log levels.

@ravishankarachanta
Copy link

thanks much

@ravishankarachanta
Copy link

ravishankarachanta commented Aug 12, 2019

I was using TimedRotatingFileHandler in my Flask app under Gunicorn with multiple workers. I ended up seeing logs from same time being written into different files (i.e one of the workers seem to be writing to a rotated file). Was trying to look thorough if thats the case with others and I see this Blog post:

https://www.packetmischief.ca/2017/10/25/3-ways-to-fail-at-logging-with-flask/?unapproved=27590&moderation-hash=51a1d5344643c9a0f5d47a253641ac53

I'm not sure if the issue is with me unable to get it working or this happens really

@SchopmanBente
Copy link

Thanks!It really helps me!

@UnSstrennen
Copy link

Thanks a lot!

@mateo2181
Copy link

mateo2181 commented Jun 3, 2020

is there a way to log errors (ex: timeout connection DB) inside gunicorn logs? Or how should I log errors in a flask app running in production with Gunicorn?

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