🌱 Junior Track 27 of 28

27. Logging & Production Diagnostics

Replace temporary `print()` statements with Python's industry-standard `logging` module. Configure Log Levels, custom `Formatter` patterns, console & file `Handler` sinks, and production rotating log files.

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 27 — LOGGING & PRODUCTION DIAGNOSTICS
# ==============================================================================
import logging
import sys

# 1. Create a Named Logger Instance
logger = logging.getLogger("AuthService")
logger.setLevel(logging.DEBUG)  # Lowest severity to capture

# 2. Define Custom Formatters
console_formatter = logging.Formatter(
    fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    datefmt="%H:%M:%S"
)

file_formatter = logging.Formatter(
    fmt="%(asctime)s | %(levelname)-8s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
)

# 3. Create Handlers (Sinks for Log Output)
# A. StreamHandler for Console / Standard Output
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)  # Console receives INFO & higher
console_handler.setFormatter(console_formatter)

# B. FileHandler for Persistent Disk Logging
file_handler = logging.FileHandler("app_audit.log", mode="a")
file_handler.setLevel(logging.DEBUG)  # File receives detailed DEBUG info
file_handler.setFormatter(file_formatter)

# 4. Attach Handlers to Logger
if not logger.handlers:
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)


# 5. Production Workflow Function
def authenticate_user(username: str, attempts: int) -> bool:
    logger.debug(f"Initiating login check for user='{username}', attempt={attempts}")
    
    if attempts > 3:
        logger.warning(f"Multiple failed attempts for user='{username}'! Locking account.")
        return False

    if username == "admin":
        logger.info(f"User '{username}' authenticated successfully.")
        return True
    else:
        logger.error(f"Authentication failed: Unknown user '{username}'.")
        return False


if __name__ == "__main__":
    print("=== Executing Production Authentication Workflows ===")
    authenticate_user("admin", 1)
    authenticate_user("unknown_user", 1)
    authenticate_user("admin", 4)
🌱 Junior Track 27 Master Reference

27. Python Logging Architecture & Handlers Guide

📁 Standard Logging Handlers

Handler Class Target Destination Best Use Case
StreamHandler `sys.stdout` / `sys.stderr` Real-time console output in containerized deployments (Docker/Kubernetes).
FileHandler Disk file (e.g. `app.log`) Persistent disk logging for background jobs and audit trails.
RotatingFileHandler Rotating disk files by size Prevents disk space exhaustion by capping log file sizes (e.g. maxBytes=10MB).
TimedRotatingFileHandler Disk files rotated by interval Daily or hourly log archiving for enterprise compliance auditing.

🏷️ Formatter Directive Format Tokens

Token Output Example Description
%(asctime)s 2026-09-20 20:25:10 Human-readable timestamp of when log record was created.
%(levelname)s INFO, ERROR Textual severity level name.
%(name)s AuthService Name of logger instance emitting the log statement.
%(filename)s:%(lineno)d auth.py:42 Source filename and line number where log call originated.
%(message)s User logged in The log message text provided by caller.

⭐ Rate Track 27: Logging Infrastructure (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 26. Debugging & Troubleshooting 🌱 Junior Hub (28 Modules Complete!) 28. JSON & Data Processing →