Ziyuan
Ziyuan

Reputation: 4568

logger.setLevel(logging.INFO) does not make logger.info() visible

I am working on Python 3.4.2 under Windows. In my case,

import logging

logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
logger.info('test')

shows nothing on the console. But

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('logger')
logger.info('test')

sucessfully shows

INFO:logger:test

I expected logger.setLevel(logging.INFO) would allow the same printout as in the second code snippet where the logger level is controlled by the root logger but it doesn't. So where's the problem? Thank you.

Upvotes: 5

Views: 3976

Answers (1)

unutbu
unutbu

Reputation: 880079

You need to add a Handler to the logger. The call to basicConfig is one way to do that.

There are many kinds of Handlers. A StreamHandler prints to the console, but there are also FileHandlers, SocketHandlers, and SMTPHandlers for instance. If you don't specify any handlers, the records aren't handled and nothing gets emitted.


To add a StreamHandler (without calling basicConfig) you could use:

import logging

logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)
console = logging.StreamHandler()
logger.addHandler(console)
logger.info('test')

This adds the StreamHandler to the logger named logger. To add the handler to the root logger, use

logging.root.addHandler(console)

By setting the Handler on the root logger, the StreamHandler may handle records generated by other loggers than just logger. Consult the logging flow diagram for a picture of when that happens.


Upvotes: 3

Related Questions