Logging Basics
Python's logging module provides structured, configurable logging. Use it instead of print() for production code.
15 min•By Priygop Team•Updated 2026
Logging
Logging
import logging
# Basic logging setup
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S"
)
logger = logging.getLogger(__name__)
# Logging levels (from lowest to highest)
logger.debug("Detailed info for debugging")
logger.info("General information")
logger.warning("Something unexpected")
logger.error("Something went wrong")
logger.critical("System is down!")
# Practical: logging in functions
def process_order(order_id, amount):
logger.info(f"Processing order {order_id}")
try:
if amount <= 0:
raise ValueError("Invalid amount")
logger.info(f"Order {order_id}: ${amount} processed")
return True
except ValueError as e:
logger.error(f"Order {order_id} failed: {e}")
return False
process_order("ORD001", 99.99)
process_order("ORD002", -50)
# Why logging > print():
# - Configurable levels (DEBUG, INFO, WARNING, ERROR)
# - Output to files, not just console
# - Timestamps and structured format
# - Can be disabled without removing codeTip
Tip
Use logging.basicConfig(level=logging.DEBUG) for quick setup. Use handlers for production: file rotation, syslog, email alerts.
Diagram
Loading diagram…
Never use print() for logging. Use __name__ for logger names. Configure once at app startup.
Common Mistake
Warning
Using print() for debugging in production. Use logging module — it supports levels, formatting, and can be disabled without removing code.
Practice Task
Note
(1) Set up basic logging with different levels. (2) Log to a file. (3) Add timestamps to log messages.