Python Logging

Python's built-in logging module provides a structured way to record application events, errors, warnings, and debugging information.

Basic Logging

Python
Write a simple log message.
import logging

logging.basicConfig(level=logging.INFO)

logging.info("Application started")
logging.warning("Low disk space")

Logging Levels

Python provides DEBUG, INFO, WARNING, ERROR, and CRITICAL levels. The level determines which messages are recorded.

Python
Use different logging levels.
logging.debug("Debug information")
logging.info("Application running")
logging.warning("Warning message")
logging.error("An error occurred")
logging.critical("Critical failure")

Customize Log Format

Python
Include time, level, and message in logs.
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("Server started")

Write Logs to a File

Python
Store application logs in a file.
import logging

logging.basicConfig(
    filename="app.log",
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("Application started")

Log Exceptions

Python
Record exception details with logging.
import logging

try:
    result = 10 / 0
except Exception:
    logging.exception("Calculation failed")

Create a Logger

Python
Create a named logger for an application module.
import logging

logger = logging.getLogger(__name__)

logger.info("User service started")
logger.error("Database connection failed")

Summary

Python logging helps developers monitor applications and diagnose problems. Use appropriate log levels, useful formatting, file handlers when needed, and exception logging for failures.