Forums

Flask logging app

I'm trying to figure out how to get logging working properly. Its works on my local machine but not here. I have the following in app.py under create_app:

# app.py in create_app():
# setup logging files
path = app.config['LOGGING_PATH']
os.makedirs(path, exist_ok=True)

info_fh = RotatingFileHandler(os.path.join(path, 'info.log'), maxBytes=10000000, backupCount=3)
info_fh.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
))
info_fh.setLevel(logging.INFO)
app.logger.addHandler(info_fh)

warning_fh = RotatingFileHandler(os.path.join(path, 'errors.log'), maxBytes=10000000, backupCount=3)
warning_fh.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
))

warning_fh.setLevel(logging.ERROR)
app.logger.addHandler(warning_fh)

I can see the directory and files have been created in the right location, but the files are empty. Some of the logging information (logging.error) shows in the server error log instead of my errors.log file, and the logging.info doesn't log to the info.log file or the server error log.

Hmm. I think what's happening is that your logging configuration is being affected by the logging setup we do to write things out to the server and error logs that are linked from the "Web" tab. What happens if, instead of using app.logger, you use the logger provided by logging.getLogger()?

Changed it to

# setup logging files
path = app.config['LOGGING_PATH']
os.makedirs(path, exist_ok=True)

info_fh = RotatingFileHandler(os.path.join(path, 'app.log'), maxBytes=10000000, backupCount=3)
info_fh.setFormatter(logging.Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
))

info_fh.setLevel(logging.INFO)
l = logging.getLogger()
l.addHandler(info_fh)

and added

import logging
logger = logging.getLogger()

to the top of all the files that have logging. Now it is writing to my file.

Thanks for the help