Table of Contents

import logging

import logging is a Python import that logs messages at different severity levels: DEBUG, INFO, WARNING, ERROR, CRITICAL. Use it instead of print() for production code.

Example

# Python
# description: configure logging, log at different levels
 
import logging
 
# Configure basic logging
logging.basicConfig(level=logging.INFO, 
                    format="%(asctime)s - %(levelname)s - %(message)s")
 
# Log messages
logging.debug("Debug message (not shown)")
logging.info("Application started")
logging.warning("This is a warning")
logging.error("An error occurred")
logging.critical("Critical failure")
 
# Get logger for a module
logger = logging.getLogger(__name__)
logger.info("Module-specific message")
 
# Log exceptions
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Division by zero occurred")

Common functions