Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
Fomalhaut Avatar asked Dec 24 '22 13:12

Fomalhaut


2 Answers

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
like image 183
ailin Avatar answered Jan 12 '23 14:01

ailin


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).

like image 37
Holloway Avatar answered Jan 12 '23 15:01

Holloway