How to Use Logging Module in Python: Simple Guide
logging module in Python by importing it and calling functions like logging.debug(), logging.info(), or logging.error() to record messages. Configure logging with logging.basicConfig() to set the output format and level.Syntax
The logging module provides functions to log messages at different levels. You start by importing the module, then configure it using logging.basicConfig(). After that, use functions like logging.debug(), logging.info(), logging.warning(), logging.error(), and logging.critical() to log messages.
The basicConfig function lets you set the minimum level of messages to show and the format of the log output.
import logging logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s') logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message')
Example
This example shows how to set up logging to print messages to the console with a simple format. It demonstrates logging messages of different severity levels. Only messages at or above the set level (INFO) are shown.
import logging # Set up logging to show INFO and above messages logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('Debug message - not shown') logging.info('Info message - shown') logging.warning('Warning message - shown') logging.error('Error message - shown') logging.critical('Critical message - shown')
Common Pitfalls
One common mistake is calling logging.basicConfig() multiple times; it only works once per program run. Another is not setting the logging level, which defaults to WARNING and hides DEBUG and INFO messages. Also, using print statements instead of logging loses the benefits of log levels and formatting.
Always configure logging once at the start of your program.
import logging # Wrong: calling basicConfig twice does nothing the second time logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.ERROR) # This call is ignored logging.info('This info message will show because level is DEBUG') logging.error('This error message will also show')
Quick Reference
| Function | Description |
|---|---|
| logging.debug(msg) | Logs a message with DEBUG level (lowest priority) |
| logging.info(msg) | Logs a message with INFO level |
| logging.warning(msg) | Logs a message with WARNING level |
| logging.error(msg) | Logs a message with ERROR level |
| logging.critical(msg) | Logs a message with CRITICAL level (highest priority) |
| logging.basicConfig() | Configures the logging system (level, format, output) |