How can I set the logging levels in Python?
I’m trying to use the standard library to debug my code. This works fine:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('message')
However, I can’t get the logger to work for the lower levels:
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info('message')
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('message')
I don’t get any response for either of these. How can I resolve this using the Python logging set level?
The issue may stem from calling logging.basicConfig()
after creating the logger. Ensure that you configure the logging level before obtaining the logger:
import logging
# Set logging level before creating the logger
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# This will show because the level is set to DEBUG
logger.debug('This is a debug message')
# Info level will also show
logger.info('This is an info message')
If you need more control over logging output, you can add custom logging handlers, such as StreamHandler:
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # Set the logger's level to DEBUG
# Set a stream handler to output to the console
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
# Add the handler to the logger
logger.addHandler(console_handler)
# Log messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logging.basicConfig()
should only be called once, as it has no effect if called multiple times. You can check the current configuration before setting it:
import logging
# Ensure that basicConfig is not called multiple times
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Log messages
logger.debug('Debug message should appear')
logger.info('Info message should appear')