Explain Codes LogoExplain Codes Logo

Python logging not outputting anything

python
logging
debugging
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 17, 2024
TLDR

Ensure logging is configured and activated with this:

import logging logging.basicConfig(level=logging.DEBUG) # Logging is now more fun than debugging with print(). logging.debug('This will actually appear') # "I'm a log message and I approve this script."

Ensure you set the log level right because DEBUG captures all levels whereas WARNING will skip anything lower (INFO).

logger.setLevel(logging.DEBUG) # A log level that even Sherlock Holmes can't ignore.

Understand that handlers are in charge of controlling where your logs go and formatters are responsible for defining their format.

handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # Time, name, level and message – nice and simple! handler.setFormatter(formatter) logger.addHandler(handler) # "Get it handled", Get it? Handler? Nevermind...

Remember to troubleshoot using proper level, handler, and formatter.

Troubleshooting

Scrutinize your Existing Handlers

If unexpected behavior occurs, inspect logging.root.handlers. Be aware that existing handlers may interfere with your basicConfig() setup.

Purge Handlers when Required

Clear non-functioning handlers using logger.handlers.clear() or logger.removeHandler(handler) to avoid conflicts and create a clean slate for new configurations.

Logger Hierarchy Matters

Improve precision and control with logger.getChild('sublogger_name') which creates sub-loggers for compartmentalized control.

Explicitly Set Logger Level

For the root logger, implement logging.root.setLevel(logging.NOTSET) to prevent filtering by the logger before reaching the handlers.

Debugging Depth

Logs in Files are Joy in Disguise

Console is too busy? Direct your log output to a file:

logging.basicConfig(filename='debug.log', level=logging.DEBUG) # "I'm a log. Find me in the file."

Logger Levels are Keys to the Kingdom

The 5-tier hierarchy - DEBUG, INFO, WARNING, ERROR, CRITICAL - allows fine control over logs. Make sure your intent matches your level setting.

Logger and Handler - The Dynamic Duo

The handler's level and the logger's level act in pair. Ensure that their settings complement each other for accurate message capture.

The Art of Advanced Configurations

For complex scenarios, use logging.config with the configuration file or dictionary for sophisticated logging strategies.

Logging Wisdom

The One-Time Show of basicConfig

logging.basicConfig() works only once as it does not affect the root logger after initial configuration.

Logger and Handler Synchronization

When adjusting levels, keep the logger and its handlers in sync, overlooking this might lead to missing log messages.

Embrace the Power of Documentation

Regularly consult the provided references for a wider understanding of scenarios and configurations.