Python Logging Module
The logging module defines functions and classes which implement a flexible event logging system for applications and libraries. It is superior to using print() statements because it allows you to categorize messages by severity and direct them to different outputs (console, files, etc.).
Importing the Module
import logging
Basic Configuration
The simplest way to configure logging is using basicConfig.
import logging
# Configure logging to show messages of level INFO and higher
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug("This is a debug message") # Won't show (level < INFO)
logging.info("This is an info message") # Will show
logging.warning("This is a warning message") # Will show
logging.error("This is an error message") # Will show
logging.critical("This is a critical message")# Will show
Logging Levels
| Level | Numeric Value | Description |
|---|---|---|
DEBUG |
10 | Detailed information, typically of interest only when diagnosing problems. |
INFO |
20 | Confirmation that things are working as expected. |
WARNING |
30 | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. 'disk space low'). |
ERROR |
40 | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
50 | A serious error, indicating that the program itself may be unable to continue running. |
Logging to a File
You can direct logs to a file by specifying the filename argument in basicConfig.
logging.basicConfig(filename='app.log', level=logging.DEBUG)
logging.info("Started application")
Advanced Usage (Loggers)
For larger applications, avoid using the root logger directly. Create a named logger.
logger = logging.getLogger(__name__)
logger.info("Message from specific module")