Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - how to write werkzeug logs to log file using RotatingFileHandler?

I've found some somewhat similar questions, but nothing that directly addresses this.

I'm trying to output all Werkzeug logging to a log file. I can get part of the logging to output to the file, but I cannot seem to capture any errors or anything beyond the basic route/request lines.

Here is what I have. How can I include ALL output from Werkzeug?

if __name__ == '__main__':
    configure_app(app)
    handler=RotatingFileHandler('server_werkzeug.log', maxBytes=10000000, backupCount=5)
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.DEBUG)
    log.addHandler(handler)
like image 518
user797963 Avatar asked Feb 04 '23 21:02

user797963


2 Answers

This code works perfectly for logging. As for the problem of not logging errors it seems, that you have to specify other loggers, besides 'werkzeug'. For traceback errors in Flask it's app.logger what you're looking for. And don't forget to set the level to WARNING.

import logging
import logging.handlers

app = Flask(__name__)

handler = logging.handlers.RotatingFileHandler(
        'log.txt',
        maxBytes=1024 * 1024)
logging.getLogger('werkzeug').setLevel(logging.DEBUG)
logging.getLogger('werkzeug').addHandler(handler)
app.logger.setLevel(logging.WARNING)
app.logger.addHandler(handler)

You can add other loggers as well, if your app is using some third party tools for like database queries, cron jobs etc.

logging.getLogger('apscheduler.scheduler').setLevel(logging.DEBUG)
logging.getLogger('apscheduler.scheduler').addHandler(handler)

The name of a logger can be found in the terminal window:

INFO:werkzeug:127.0.0.1 - - [10/Mar/2018 15:41:15] "GET /file.js HTTP/1.1" 200 -
DEBUG:apscheduler.scheduler:Next wakeup is due at 2018-03-10 16:00:00+03:00 (in 1124.668881 seconds)
like image 110
Tim Nikitin Avatar answered Feb 07 '23 10:02

Tim Nikitin


Use the dictConfig is a more extendable way.

from logging.config import dictConfig

dictConfig({
    'version': 1,
    'handlers': {
        'file.handler': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'server_werkzeug.log',
            'maxBytes': 10000000,
            'backupCount': 5,
            'level': 'DEBUG',
        },
    },
    'loggers': {
        'werkzeug': {
            'level': 'DEBUG',
            'handlers': ['file.handler'],
        },
    },
})
like image 33
Yan QiDong Avatar answered Feb 07 '23 11:02

Yan QiDong