Jones
Jones

Reputation: 1214

Python logging module not logging info even after level is set

I'm trying to do some basic logging. I'm doing the following:

log = logging.getLogger('test')

log.error('test') # 'test' gets logged

log.info('test') # Nothing gets logged, as expected

log.setLevel(logging.INFO) # Now info should be logged, right?

log.info('test') # No output

log.setLevel(logging.INFO) # Getting desperate

log.info('test') # Still nothing

What aspect of the logging module am I missing?

Upvotes: 3

Views: 1468

Answers (3)

Ytsen de Boer
Ytsen de Boer

Reputation: 3107

It is not necessary to call basicConfig.

However, the issue is about handlers (as pointed out by @Mahesh Karia).

You see, if you don't define some handlers you are dependent on whatever is already "in place" for you and that raises lots of confusion.

Check this:

You create your "test" logger

>>> log = logging.getLogger('test')

which prints WARNING messages but does not print INFO messages even after setting the level to INFO:

>>> log.warning('hi')
hi
>>> log.setLevel(logging.INFO)
>>> log.info('hi')
>>> 

(personally, I think this is very wrong behaviour)

It can be "solved" by manipulating "handlers".

Your "test" logger has none

>>> log.handlers
[]

nor does it parent, the "root logger"

>>> log.parent
<RootLogger root (WARNING)>
>>> log.parent.handlers
[]

however, one can add a handler easy enough (to the root logger)

>>> log.parent.addHandler(logging.StreamHandler())

and now your "test" logger "works":

>>> log.info('hi')
hi

PS. Was using Python 3.8.2 prompt after importing logging module.

Upvotes: 0

be_good_do_good
be_good_do_good

Reputation: 4441

You need to configure logging before you use it like below. You can configure it beautifully in python.

logging.basicConfig(format='%(asctime)s %(name)25s %(lineno)4d %(levelname)8s: %(message)s', level=40)

above statement will print timestamp, name of the file, line number, level type, message

level of logging also can be set during basic Config itself (40 = ERROR)

Upvotes: 1

Mahesh Karia
Mahesh Karia

Reputation: 2055

You have forgot to add handlers i.e. logging.basicConfig(), can you check if following code works for you.

import logging
logging.basicConfig()
log = logging.getLogger('test')
log.setLevel(logging.INFO)
log.error('test')
log.info('test')

Upvotes: 9

Related Questions