Python for Data Analytics & AutomationLesson 39 of 41
Lesson 39 of 41

Production Analytics Engineering: Custom Exceptions & logging Module

Overview & Learning Objectives

In production environments, using `print()` statements is unacceptable: prints lack timestamps, cannot be routed to rotating log files, cannot be filtered by severity level, and disappear when terminal sessions close. Professional analytics engineering requires the Python standard `logging` module to capture diagnostic telemetry (DEBUG, INFO, WARNING, ERROR, CRITICAL) alongside domain-specific custom exceptions that fail fast when data quality anomalies appear.

  • Configure production loggers with file and console handlers, formatting, and severity level filtering.
  • Define domain-specific custom exceptions (`DataValidationError`, `SchemaMismatchError`) for transparent debugging.
  • Implement defensive `try...except...else...finally` control flows for robust resource cleanup.

Industry Standard

Standard: Production data pipelines at Netflix and Airbnb mandate structured JSON log output with unique run IDs, enabling centralized log aggregation in Datadog and Splunk.

Real-World Example: ScoopCraft POS Ingestion Data Quality Firewall

ScoopCraft data pipelines log all record transformations and raise custom exceptions when daily revenues fall below zero or duplicate primary keys appear.

Log LevelTimestampLogger NameEvent Message
INFO2026-11-13 06:01:02scoopcraft.etlStarting POS file ingestion for 15 dark-store locations
WARNING2026-11-13 06:01:14scoopcraft.qualityDark store BLR-04 has 12 orders with zero delivery times
ERROR2026-11-13 06:01:25scoopcraft.dbDatabase connection timeout on replica 2; retrying...
CRITICAL2026-11-13 06:01:40scoopcraft.etlSchemaMismatchError: Missing required column [Order_ID]

Syntax & Core Code Implementation

import logging
from pathlib import Path

# Configure production logging with file and console output
log_file = Path('pipeline.log')
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] (%(name)s): %(message)s',
    handlers=[
        logging.FileHandler(log_file, encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger('DarkStoreETL')

# Custom Domain Exception
class DataQualityException(Exception):
    """Raised when incoming dataset violates business assertions."""
    pass

def process_daily_sales(df):
    logger.info(f"Processing sales dataframe with {len(df)} rows.")
    
    if 'Order_ID' not in df.columns:
        logger.critical("Fatal: Order_ID column missing!")
        raise DataQualityException("Input data is missing mandatory 'Order_ID' column.")
        
    negative_sales = (df['Sales'] < 0).sum()
    if negative_sales > 0:
        logger.warning(f"Detected {negative_sales} negative sales transactions. Flagging for review.")
        
    logger.info("Sales processing completed successfully.")

Parameters & Arguments Breakdown

  • level: Minimum logging threshold (DEBUG=10, INFO=20, WARNING=30, ERROR=40, CRITICAL=50).
  • format: Format string specifying tokens like %(asctime)s, %(levelname)s, and %(message)s.
  • handlers: Destinations for log messages (FileHandler for disk persistence, StreamHandler for console output).

Step-by-Step Implementation

  1. Instantiate Module Logger: Call `logger = logging.getLogger(__name__)` at top of every module.
  2. Replace Print Calls: Substitute informative status messages with `logger.info()` and diagnostic details with `logger.debug()`.
  3. Implement Clean Cleanup: Use `finally:` blocks or context managers to guarantee database cursors and file descriptors close on error.

Common Mistakes & Limitations

  • Catching bare exceptions (`except: pass`), which suppresses keyboard interrupts (Ctrl+C), out-of-memory errors, and bugs silently.
  • Using `logger.error(e)` without stack traces; use `logger.exception("Context message")` inside except blocks to automatically capture the full traceback.
  • Configuring `basicConfig()` multiple times in different files, which has no effect after the first invocation.

Keyboard Shortcuts (Jupyter & VS Code)

ActionWindowsMac
Go to Symbol / Class definition in fileCtrl + Shift + OCmd + Shift + O

Pro Tips & Modern Best Practices

  • Inside an `except` block, always call `logger.exception("Error during execution")`—it automatically attaches the entire multi-line traceback.
  • Use `RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5)` to automatically rotate logs once files reach 10MB.
Production Analytics Engineering: Custom | DataCliq