Fomalhaut
Fomalhaut

Reputation: 9727

Why does my logging not work in Python 3?

I am trying to add a logging handler in Python 3 this way:

$ python3
Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> 
>>> logger = logging.getLogger()
>>> handler = logging.StreamHandler()
>>> handler.setLevel(logging.INFO)
>>> logger.addHandler(handler)
>>> 
>>> logging.info("my info")
>>> logging.warning("my warning")
my warning

I specified loglevel as INFO. Why does logging.info("my info") output nothing?

Upvotes: 4

Views: 4627

Answers (3)

flowfelis
flowfelis

Reputation: 148

This works:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('hello world!')

Or this also works:

import logging

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info('hello world!')

This DOES NOT work:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info('hello world!')

Upvotes: -1

Holloway
Holloway

Reputation: 7367

Loggers have levels as well as handlers. The default level is warn so your info is ignored.

To get your example to work, include logger.setLevel(logging.INFO).

Upvotes: 2

ailin
ailin

Reputation: 501

because you need to set logger lever as well.

import logging

logger = logging.getLogger()
# here
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
logger.addHandler(handler)

output:

>>> logging.info("my info")
my info
>>> logging.warning("my warning")
my warning

Upvotes: 9

Related Questions