Home > OS >  Python logger not showing DEBUG level messages even though handler level is set to debug
Python logger not showing DEBUG level messages even though handler level is set to debug

Time:05-22

I'm trying to create a logger that prints "debug" messages. I've defined handlers with the correct level set. Still it only prints warning levels and above.

This is my code:

import logging

# Create a custom logger
logger = logging.getLogger(__name__)

# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('file.log')
c_handler.setLevel(logging.DEBUG)
f_handler.setLevel(logging.DEBUG)

# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)

logger.warning('This is a warning')
logger.error('This is an error')
logger.info('This is an info')
logger.debug('This is a debug')

While this is the console output I get:

__main__ - WARNING - This is a warning
__main__ - ERROR - This is an error

Process finished with exit code 0

I've found similar posts about this problem, but in that case the handlers were not set. My handlers are set.

What's wrong here?

PS: Code is a slightly altered version of this page, section "using handlers".

CodePudding user response:

You are forgetting to set the logger level

import logging

# Create a custom logger
logger = logging.getLogger(__name__)

# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('file.log')

# handler level is different from logger level
c_handler.setLevel(logging.DEBUG)
f_handler.setLevel(logging.DEBUG)

# this will do the trick
logger.setLevel(logging.DEBUG)

# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)

# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)

logger.warning('This is a warning')
logger.error('This is an error')
logger.info('This is an info')
logger.debug('This is a debug')

You can find more info here

  • Related