Python Forum

Full Version: flask How to output stderr and exceptions to log file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have flask application which simple logger setup

  logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)
    handler = RotatingFileHandler("/logs/logger.log", maxBytes=20480000, backupCount=50)
    error_handler = RotatingFileHandler("/logs/error_logger.log", maxBytes=20480000, backupCount=50)
    error_handler.setLevel(logging.ERROR)
    logger.addHandler(handler)
    logger.addHandler(error_handler)
the problem is that when i have for example error like this is dons't writen to log:

 Traceback (most recent call last):
      File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
        exec(compile(contents+"\n", file, 'exec'), glob, loc)
      File "C:/git/myapp.py", line 125, in <module>
        logger.info("In read_file - create_log_history - Copying log from %s to %s" % (notice_msg))
    TypeError: not enough arguments for format string
how can i set up the logger to write Traceback errors to log ?
there is exc_info parameter for logger
logger.error('my error', exc_info=1)
which with any true-ish value will log traceback as well
the problem is i want flask to write to the log without me scatter errors logs all over
Flask has build in support for Logging.
Using dictConfig can eg setup like this.
Now will flask.log be in the static folder.
from flask import Flask, render_template, jsonify, request
from logging.config import dictConfig

dictConfig({
    'version': 1,
    'handlers': {
        'file.handler': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'static/flask.log',
            'maxBytes': 10000000,
            'backupCount': 5,
            'level': 'DEBUG',
        },
    },
    'loggers': {
        'werkzeug': {
            'level': 'DEBUG',
            'handlers': ['file.handler'],
        },
    },
})

app = Flask(__name__)
Thanks, but this is not what i was asking, i need to find way to output Traceback to the log , without me scatter around log's