pr0grammingIsFun
pr0grammingIsFun

Reputation: 35

python logging to file vs console with certain logLevel

import logging
import sys

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

file_handler = logging.FileHandler('test.log')
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)

console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG)
logger.addHandler(console_handler)

logger.info('Info print')
logger.debug('Debug print')

I have simple code above. How come the debug statement doesn't print? It seems like the logLevel is always determined by line 5. The file_handler.setLevel and the console_handler.setLevel seem to do nothing. I want to eventually have debug prints going to the test.log file, and info prints going to the console.

Upvotes: 0

Views: 109

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99365

The logger and handler levels are both used, but at different times. The logger's level is inspected first, and if the event severity level is >= the logger's level, then the event is passed to handlers. The event's level is then checked against each handler's level to determine if that handler handles the event.

Upvotes: 1

Related Questions