variable
variable

Reputation: 9736

How to log INFO messages from the non-root logger?

I know that default level for root logger is warning (30). If I create a non-root logger and if there is no handler defined on that, then the logger will use the level of the root logger (and handler of the root logger). What is the handler level for the root handler?

#assume no root logger is configured and below code gets the non-root logger for the module
logger = logging.getLogger(__name__)
#get effective level - this is inherited from the root logger
print(logger.getEffectiveLevel())
#set the level for this logger to 10
logger.setLevel(10)
#print level which shows 10
print(logger.getEffectiveLevel())
logger.info('this does not get logged')
logger.warning('this gets logged')

How can I get info to print?

Upvotes: 2

Views: 349

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40948

The logger doesn't have any handlers explicitly attached to it by default:

>>> logger.handlers
[]

However, in the .callHandlers() method, the logging module will actually fall back to a lastResort handler that has a level of WARNING:

_defaultLastResort = _StderrHandler(WARNING)
lastResort = _defaultLastResort

# ....

    if (found == 0):
        if lastResort:
            if record.levelno >= lastResort.level:
                lastResort.handle(record)

As indicated in the comments, attaching a handler to logger, either viaa basicConfig() or explicitly through addHandler(), and then setting the level of that handler, will mean the logger doesn't fall back to lastResort.

Upvotes: 2

Related Questions