Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect python flask werkzeug logs to a log file when using TimedRotatingHandler?

Tags:

python

logging

I've created a TimedRotatingHandler for the Flask server. But all the logs generated by the werkzeug are still thrown on the console.

How can I redirect these logs to the log file(test.log) with the log rotating functionality.

Code snippet:

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
# add a file handler
fh = logging.handlers.TimedRotatingFileHandler("test.log",when='M',interval=1,backupCount=0)
fh.setLevel(logging.DEBUG)
# create a formatter and set the formatter for the handler.
frmt = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh.setFormatter(frmt)
# add the Handler to the logger
log.addHandler(fh)
app.run(host='0.0.0.0', debug=True)

The below logs are still thrown on the console.

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET / HTTP/1.1" 200 -
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /static/js/jquery-1.11.2/jquery-1.11.2.min.js HTTP/1.1" 304 -
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /static/js/main/main.js HTTP/1.1" 304 -
192.168.1.6 - - [25/Jun/2015 07:11:13] "GET /favicon.ico HTTP/1.1" 404 -

Adding the log file handler to the werkzeug logger is too not solving the problem

logging.getLogger('werkzeug').addHandler(fh);
like image 736
karthik.zorfy Avatar asked Jun 25 '15 11:06

karthik.zorfy


3 Answers

To change werkzeung logging you need to override logging.root.handler like:

import logging
from logging.handlers import RotatingFileHandler

handler = RotatingFileHandler('log.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.ERROR)

logging.root.handlers = [handler]

See here for details.

like image 185
Alex Revetchi Avatar answered Nov 12 '22 20:11

Alex Revetchi


It looks like werkzeug sends it messages to the root logger rather than a named logger.

If you try this it should start logging to your file logging.getLogger().addHandler(fh)

If you want it to stop logging to the console then you'll have to remove the stream handler from the root logger. You can see the handlers for the root logger by using

>>> print logging.getLogger().handlers [<logging.StreamHandler object at 0x.....>, logging.handlers.TimedRotatingFileHandler object at 0x.....>]

like image 2
walrusVision Avatar answered Nov 12 '22 19:11

walrusVision


In order to direct the flask server/app log to a file handler and also werkzeug to same file handler, you may want to do something like the following.

handler = RotatingFileHandler('test.log', maxBytes=1000000, backupCount=5)
handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler)
log = logging.getLogger('werkzeug')
log.setLevel(logging.DEBUG)
log.addHandler(handler)
app.run(host='0.0.0.0', debug=True)
like image 1
spanchan Avatar answered Nov 12 '22 19:11

spanchan