Tahini245
Tahini245

Reputation: 13

Why isn't my Python logging setup working?

My code looks like this

import logging

formatter = logging.Formatter("{asctime} - {name} - {levelname} - {message}",
                              "%d-%b-%y %H:%M", "{")


def _add_handler(handler: logging.StreamHandler) -> logging.StreamHandler:
    handler.setFormatter(formatter)
    handler.setLevel(20)
    return handler

logging.basicConfig(
    handlers={
        _add_handler(logging.FileHandler("filename.log")),
        _add_handler(logging.StreamHandler())
    })
logging.info("hello world")

What this is supposed to do is log "hello world" both to the console and a file named filename.log, with a severity of INFO, which is what the 20 in the setLevel method is for. However, nothing is being logged at all. Where have I gone wrong?

Upvotes: 1

Views: 46

Answers (1)

chepner
chepner

Reputation: 532303

You need to set the logging level for the logger as well. By default, it's set to logging.WARNING, so neither handler is seeing the message, let alone determining if it should be handled.

logging.basicConfig(
    level=logging.INFO,
    handlers={
        _add_handler(logging.FileHandler("filename.log")),
        _add_handler(logging.StreamHandler())
    })

Upvotes: 1

Related Questions