Rizhiy
Rizhiy

Reputation: 854

Lower logging level for single logger

I use a package which logs too much. It has loggers set up properly, so I can get individual loggers using getLogger.

Is it possible to decrease logging level for all message produced by particular logger?

I know there is setLevel function, which disables all messages below certain level, but I still want the messages to be logged, just on a lower level, e.g. INFO level messages should instead be logged at DEBUG.

Upvotes: 0

Views: 1449

Answers (1)

blues
blues

Reputation: 5185

It depends what exactly you want to happen. You could either use a Filter or an Adapter to modify the log level.

A filter is easier, but only works properly for downgrading the log level.

The adapter solution has the advantage of setting the level at the earliest possible moment. The adapter has the downside of just being a wrapper around the logger, so you need to pass it to all places that would use the logger. If that's a third-party module the adapter solution won't be possible.

# Using filters
import logging

def changeLevel(record):
    if record.levelno == logging.INFO:
        record.levelno = logging.DEBUG
        record.levelname = "DEBUG"
    return record

logger = logging.getLogger('name')
logger.addFilter(changeLevel)
# Using an adapter
import logging

class ChangeLevel(logging.LoggerAdapter):
    def log(self, level, msg, *args, **kwargs):
        if level == logging.INFO:
            level = logging.DEBUG
        super().log(level, msg, args, kwargs)

logger_ = logging.getLogger('name', {})
logger = ChangeLevel(logger_)

Upvotes: 2

Related Questions