Skip to content

agfianf/python-logger-monitoring

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Python Logging with Loki + Grafana

Overview Workflow

A modern centralized logging system for Python apps using the latest observability stack:

  • Python with structlog (structured logging)
  • Loki (log aggregation & storage)
  • Promtail (log shipper)
  • Grafana (visualization & dashboards)

πŸ“‹ What You'll Learn

This tutorial will teach you:

  1. βœ… Structured Logging with Python structlog
  2. βœ… Log Aggregation using Loki
  3. βœ… Log Shipping with Promtail
  4. βœ… Real-time Visualization in Grafana
  5. βœ… Business Logic Simulation for testing

Running this:

make up
# or 
docker-compose up --build

πŸ” Dashboard Grafana Result

Loki Dashboard

Click to show demo loki

Loki Dashboard Loki Dashboard Loki Dashboard Loki Dashboard


πŸ—‚οΈ Project Structure

python-logging-loki/
β”œβ”€β”€ app/                          # 🐍 Python application
β”‚   β”œβ”€β”€ main.py                   # Entry point & request simulation
β”‚   β”œβ”€β”€ business_logic.py         # Simulated business operations
β”‚   └── log_config.py             # structlog configuration
β”œβ”€β”€ config/                       # βš™οΈ Service configurations
β”‚   β”œβ”€β”€ loki-config.yml           # Loki configuration
β”‚   β”œβ”€β”€ promtail-config.yml       # Promtail log collection rules
β”‚   β”œβ”€β”€ grafana-datasources.yml   # Grafana data sources
β”‚   └── grafana-dashboards.yml    # Dashboard provisioning
β”œβ”€β”€ dashboards/                   # πŸ“Š Grafana dashboards
β”‚   └── structlog-dashboard.json
β”œβ”€β”€ docker-compose.yml            # 🐳 Orchestration
└── Dockerfile                    # πŸ“¦ Python app container

πŸ”„ How the System Works

graph TD
    A[Python App] -->|JSON Logs| B[Docker Logs]
    B -->|Scrape| C[Promtail]
    C -->|Ship| D[Loki]
    D -->|Query| E[Grafana]
    E -->|Dashboard| F[User]
Loading

πŸ“Š Detailed Logging Journey

Click to expand

πŸ›€οΈ Complete Log Flow Diagram

graph TB
    subgraph "Python Application Container"
        A1[structlog Logger] --> A2[JSON Processor]
        A2 --> A3[Mask Sensitive Data]
        A3 --> A4[Normalize Fields]
        A4 --> A5[stdout/stderr]
    end
    
    subgraph "Docker Engine"
        A5 --> B1[Docker JSON Driver]
        B1 --> B2[Log Files<br>/var/lib/docker/containers/...]
    end
    
    subgraph "Promtail Container"
        B2 --> C1[File Discovery]
        C1 --> C2[JSON Parser]
        C2 --> C3[Label Extraction]
        C3 --> C4[Stream Processing]
    end
    
    subgraph "Loki Container"
        C4 --> D1[Log Ingestion API]
        D1 --> D2[Index Creation]
        D2 --> D3[Chunk Storage]
        D3 --> D4[Query Engine]
    end
    
    subgraph "Grafana Container"
        D4 --> E1[LogQL Queries]
        E1 --> E2[Data Processing]
        E2 --> E3[Dashboard Panels]
        E3 --> E4[User Interface]
    end
    
    style A1 fill:#e1f5fe
    style B2 fill:#f3e5f5
    style C4 fill:#e8f5e8
    style D3 fill:#fff3e0
    style E4 fill:#fce4ec
Loading

πŸ” Step-by-Step Log Journey

1️⃣ Python App β†’ structlog Processing

πŸ“ Code Execution
    ↓
πŸ”§ structlog Processors:
    β€’ mask_sensitive_processor()     β†’ Hide passwords/tokens
    β€’ normalize_high_cardinality()   β†’ Replace UUIDs with {uid}
    β€’ TimeStamper()                  β†’ Add ISO timestamp
    β€’ JSONRenderer()                 β†’ Convert to JSON
    ↓
πŸ“€ Output to stdout/stderr

Example Log Output:

{
  "xtime": "2024-01-15T10:30:45.123456",
  "level": "info",
  "msg": "User login successful",
  "request_id": "req-123",
  "user_id": 456,
  "method": "POST",
  "path": "/api/v1/auth/login",
  "password": "***MASKED***"
}

2️⃣ Docker β†’ Log Capture

🐳 Docker Container
    ↓
πŸ“‹ JSON File Driver
    ↓
πŸ’Ύ File Storage: /var/lib/docker/containers/{container_id}/{container_id}-json.log

Docker Log Format:

{
  "log": "{\"xtime\":\"2024-01-15T10:30:45.123456\",\"level\":\"info\"...}\n",
  "stream": "stdout",
  "time": "2024-01-15T10:30:45.123456789Z"
}

3️⃣ Promtail β†’ Log Collection

πŸ” Docker Service Discovery
    ↓
πŸ“‚ File Monitoring (/var/lib/docker/containers/**/*.log)
    ↓
🏷️ Label Extraction from Docker containers:
    β€’ container_name
    β€’ logging_jobname (from labels)
    β€’ logging="promtail" (filter)
    ↓
πŸ“Š JSON Parsing & Stream Processing
    ↓
πŸš€ HTTP Push to Loki API

Promtail Processing:

  • Discovery: Auto-detect containers with logging: "promtail" label
  • Parsing: Extract JSON from Docker's nested format
  • Labeling: Add metadata (job, container, etc.)
  • Streaming: Real-time push to Loki

4️⃣ Loki β†’ Log Storage

πŸ“¨ HTTP API Ingestion (/loki/api/v1/push)
    ↓
🏷️ Index Creation (based on labels):
    β€’ job="jobname-auth-service"
    β€’ container_name="auth-service"
    β€’ level="info"
    ↓
πŸ“¦ Chunk Creation (grouped by time + labels)
    ↓
πŸ’Ύ Storage (local filesystem or cloud)

Loki Storage Structure:

chunks/
β”œβ”€β”€ fake/
β”‚   └── {chunk-id}/
β”‚       β”œβ”€β”€ {time-range}-{hash}.gz  # Compressed log data
β”‚       └── index                   # Label index

5️⃣ Grafana β†’ Visualization

πŸ” LogQL Query:
    {job="jobname-auth-service"} |= "login" | json | level="info"
    ↓
πŸ“Š Query Engine Processing
    ↓
πŸ“ˆ Panel Rendering:
    β€’ Time series graphs
    β€’ Log tables
    β€’ Stat panels
    ↓
πŸ–₯️ Dashboard Display

πŸ”§ Data Transformation Examples

Raw Python Log β†’ Final Grafana Display

1. Python structlog:

logger.info("Order processed", 
    order_id="order-550e8400-e29b-41d4-a716-446655440000",
    user_id=123,
    amount=99.99,
    payment_method="credit_card")

2. After structlog processing:

{
  "xtime": "2024-01-15T10:30:45.123456",
  "level": "info", 
  "msg": "Order processed",
  "order_id": "order-{uid}",  // ← Normalized!
  "user_id": 123,
  "amount": 99.99,
  "payment_method": "credit_card"
}

3. Docker wrapping:

{
  "log": "{\"xtime\":\"2024-01-15T10:30:45.123456\",\"level\":\"info\"...}\n",
  "stream": "stdout",
  "time": "2024-01-15T10:30:45.123456789Z"
}

4. Promtail adds labels:

{
  "streams": [{
    "stream": {
      "job": "jobname-auth-service",
      "container_name": "auth-service",
      "level": "info"
    },
    "values": [["1705315845123456000", "{\"xtime\":\"2024-01-15T10:30:45.123456\"...}"]]
  }]
}

5. Grafana LogQL query:

{job="jobname-auth-service"} 
|= "Order processed" 
| json 
| amount > 50

⚑ Performance & Optimization

πŸ“Š Throughput Capacity:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Component   β”‚ Logs/Second  β”‚ Bottleneck  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ structlog   β”‚ 10,000+      β”‚ CPU         β”‚
β”‚ Docker      β”‚ 5,000+       β”‚ Disk I/O    β”‚
β”‚ Promtail    β”‚ 3,000+       β”‚ Network     β”‚
β”‚ Loki        β”‚ 2,000+       β”‚ Storage     β”‚
β”‚ Grafana     β”‚ 1,000+       β”‚ UI Render   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Flow Details:

  1. 🐍 Python App β†’ Generates structured JSON logs using structlog
  2. πŸ“‹ Promtail β†’ Reads logs from Docker containers in real-time
  3. πŸ—„οΈ Loki β†’ Stores and indexes logs for fast querying
  4. πŸ“Š Grafana β†’ Displays logs in interactive dashboards

πŸš€ Quick Start (5-Minute Setup!)

Prerequisites

  • Docker & Docker Compose installed
  • Port 3000 (Grafana) available

1. Clone & Run

# Clone this repository
cd python-logging-loki

# Start all services
docker-compose up --build

2. Access the Dashboard

3. View Real-time Logs

The dashboard instantly shows:

  • βœ… Request logs with response times
  • βœ… Error tracking and alerts
  • βœ… Business operation metrics
  • βœ… User activity patterns

πŸ“± Business Logic Simulation

This app simulates real-world business scenarios:

πŸ§‘β€πŸ’Ό User Operations

# User registration with validation
simulate_user_registration(user_data)

# Authentication with security logging
simulate_authentication(username, password)

πŸ›’ E-commerce Operations

# Order processing with inventory & payment
simulate_order_processing(order_data)

# File upload with virus scanning
simulate_file_upload(filename, file_size)

πŸ“Š Analytics & Performance

# Data analytics with performance monitoring
simulate_data_analytics(query_type)

🎯 Log Types Generated:

  • INFO: Successful operations
  • WARNING: Business logic warnings
  • ERROR: System/business errors
  • DEBUG: Development details

βš™οΈ Service Configuration

🐍 Python App (app/)

  • structlog: Structured JSON logging
  • Rotating logs: Auto cleanup (10MB files)
  • Sensitive data masking: Password/token masking
  • Request tracing: UUID-based request tracking

πŸ“‹ Promtail (config/promtail-config.yml)

# Key features:
- Docker log discovery
- JSON parsing
- Label extraction
- Health check filtering
- Timestamp parsing

πŸ—„οΈ Loki (config/loki-config.yml)

  • Retention: 30 days by default
  • Indexing: Optimized for JSON logs
  • Performance: Great for development

πŸ“Š Grafana (config/)

  • Auto-provisioning: Data sources & dashboards
  • Anonymous access: No login required
  • Custom dashboard: Pre-built for structlog

πŸ“– References

About

Show simple setup to log your python app, and monitoring that using grafana, loki, and promtail

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published