1
votes

I have a Flask web application and Python Logging configuration is done via dictConfig on application startup. A handler for writing certain logs to database is attached to logger 'test.module' Logs made to that logger are written to database only if logging.basicConfig(level=logging.DEBUG) is also called at application startup. Otherwise no logs are written to database. I know that basicConfig just attaches a streamHandler to root logger. I think this should be irrelevant because I don't want anything to be done by root logger. Why is this not working without basicConfig?

I added how I initiate the loggers and my configuration below.

class DbHandler(logging.Handler):
    def __init__(self, level=logging.NOTSET):
        logging.Handler.__init__(self, level)

    def emit(self, record):
        record.message = self.format(record)
        log = DbModel()
        log.message = record.message
        log.save()


LOGGING = {
    'version': 1,
    'handlers': {
        'db_log': {
            'level': 'DEBUG',
            'class': 'test.handlers.DbHandler',
        },
    },
    'loggers': {
        'test.important_module': {
            'handlers': [
                'db_log'
            ],
    },
}

# logging.basicConfig(level=logging.DEBUG) # Doesnt work without this
logging.config.dictConfig(LOGGING)

logger = logging.getLogger('test.important_module')
logger.info('Making a test')
1
Can you the code you are using to setup the logger and how that relates to the code doing the actual logging? What you have provided so far is somewhat vague... - isedev
@isedev I added it now - refik
Just from a usability perspective, I'd rethink having the handler modify record.message as a side-effect. Just set log.message = self.format(record) directly. - Silas Ray

1 Answers

5
votes

You are not setting the level for the 'test.important_module' logger itself (you only set the level for the handler).

You can do it like this:

logger = logging.getLogger('test.important_module')
logger.setLevel(logging.DEBUG)

Or like this:

'loggers': {
    'test.important_module': {
        'level': 'DEBUG',         # <<< HERE
        'handlers': [
            'db_log'
        ],
},