Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask properly configure logging

I created a simple flask application but can't get logging configured properly.

def configure_logger(log_path, name='default'):
    logging.config.dictConfig({
        'version': 1,
        'formatters': {
            'default': {'format': '%(asctime)s - %(levelname)s - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}
        },
        'handlers': {
            'console': {
                'level': 'INFO',
                'class': 'logging.StreamHandler',
                'formatter': 'default',
                'stream': 'ext://sys.stdout'
            },
            'file': {
                'level': 'INFO',
                'class': 'logging.handlers.TimedRotatingFileHandler',
                'formatter': 'default',
                'when': 'midnight',
                'filename': log_path,
                'backupCount': 5
            }
        },
        'loggers': {
            'default': {
                'level': 'INFO',
                'handlers': ['console', 'file']
            }
        },
        'disable_existing_loggers': False
    })
    return logging.getLogger(name)

and

logger = configure_logger(log_path='./logs/')
app.logger.addHandler(logger)

But the (flask )logger is not using the supplied configuration, and when logging in a submodule

├── api.py
├── logs
├── my_pkg
│   ├── __init__.py
│   └── second.py
└── settings
    ├── __init__.py
    └── settings.py

I only get errors logged and my logging configuration again is not applied for a logger in the submodule:

import logging
logger = logging.getLogger('root')

https://github.com/geoHeil/flask_logging_question showcases this in a sample project

like image 699
Georg Heiler Avatar asked Sep 08 '25 13:09

Georg Heiler


1 Answers

Enabling 'disable_existing_loggers': False` as outlined by https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ will help to solve the problem.

like image 143
Georg Heiler Avatar answered Sep 10 '25 01:09

Georg Heiler