0

I have the following simple test script:

import logging
import sys


logger = logging.getLogger(__name__)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'$
logger.addHandler(handler)


logger.info('Hello World!')
logger.warning('Bad!')

I run this script with python test.py in the command line. I get:

__main__ - WARNING - Bad!

When I expected to get:

__main__ - WARNING - Bad!
__main__ - INFO - Hello World!

E.g. I expected both the info and warning log messages to get printed to the console window, but only the warning message did. How come?

Aleksey Bilogur
  • 3,686
  • 3
  • 30
  • 57

2 Answers2

2

This should work?

import logging
import sys


logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)


logger.info('Hello World!')
logger.warning('Bad!')

You should be setting the setLevel on the logger object.

Thanks

Gagan
  • 5,416
  • 13
  • 58
  • 86
1

I think What is the point of setLevel in a python logging handler? contains answer.

You need to setLevel on logger itself too, its level (default WARNING) will not allow messages from it's handlers with lower level than set in parent-logger.

Handler is there to filter messages.

Damian
  • 548
  • 6
  • 14