Mazyod
Mazyod

Reputation: 22569

Python logging strange behavior

Consider this code:

ubuntu_logger = logging.getLogger('ubuntu-logger')

mail_handler = MailHandler()
mail_handler.setLevel(logging.INFO)
ubuntu_logger.addHandler(mail_handler)

filepath = "/home/ubuntu/logs/central.log"
formatter = logging.Formatter('[%(asctime)s - %(name)s - %(levelname)s]: %(message)s')

central_handler = logging.handlers.RotatingFileHandler(
    filename=filepath,
    mode="a+"
)
central_handler.setLevel(logging.DEBUG)
central_handler.setFormatter(formatter)
ubuntu_logger.addHandler(central_handler)

I create this handler in serverutils.logutils, a custom python module. Then, I import it into my daemon service script, which is run by root user:

from serverutils.logutils import ubuntu_logger as logger, DEFAULT_LOGGING_CONFIG

logger.info('pydaemons launching...')

With the code above, the ubuntu_logger simply does nothing at all. After changing the code like below, ubuntu_logger works as expected, in addition to the root logger:

import logging
from serverutils.logutils import ubuntu_logger as logger, DEFAULT_LOGGING_CONFIG

config = DEFAULT_LOGGING_CONFIG # Fancy format, log level DEBUG
config.update(filename='/home/ubuntu/test.log')

logging.basicConfig(**config)

logging.error('omg, this works')
logger.info('pydaemons launching...')

What am I missing?

Upvotes: 0

Views: 390

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125018

You'll need to set a log level on ubuntu_logger:

ubuntu_logger.setLevel(logging.DEBUG)

otherwise it'll find the WARNING level set by default on the root logger instead. When you ran logging.basicConfig() you set the log level of the root logger to DEBUG, so the ubuntu_logger picked that up and no longer filtered your INFO level log messages.

What normally happens when you call one of the logger.log() helper functions (such as logger.info()) is that the logger checks if the current level allows for that message. If it's own level is NOTSET (the default), the parent log object is consulted, etc. until the root is found, where the default is WARNING.

You may want to disable log propagation if you have handlers set on a specific logger:

ubuntu_logger.propagate = False

otherwise the root logger is also asked to handle the log message. Propagation does not affect at what level a logger starts emitting messages.

Upvotes: 2

Related Questions