Python observability patterns including structured logging

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Python observability cover

Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.

---
name: python-observability
description: Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.
---

# Python Observability

Instrument Python applications with structured logs, metrics, and traces. When something breaks in production, you need to answer "what, where, and why" without deploying new code.

## When to Use This Skill

- Adding structured logging to applications
- Implementing metrics collection with Prometheus
- Setting up distributed tracing across services
- Propagating correlation IDs through request chains
- Debugging production issues
- Building observability dashboards

Overview

Instrument Python applications with structured logs, metrics, and traces. When something breaks in production, you need to answer "what, where, and why" without deploying new code.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill python-observability -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-observability
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/4bab6e6ba5ccb5a63343/python-observability.zip" -OutFile "$env:TEMP\python-observability.zip"; Expand-Archive "$env:TEMP\python-observability.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md6.9 KB
  • references/1 file · 4.9 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text230 lines

Python Observability

Instrument Python applications with structured logs, metrics, and traces. When something breaks in production, you need to answer "what, where, and why" without deploying new code.

When to Use This Skill

  • Adding structured logging to applications
  • Implementing metrics collection with Prometheus
  • Setting up distributed tracing across services
  • Propagating correlation IDs through request chains
  • Debugging production issues
  • Building observability dashboards

Core Concepts

1. Structured Logging

Emit logs as JSON with consistent fields for production environments. Machine-readable logs enable powerful queries and alerts. For local development, consider human-readable formats.

2. The Four Golden Signals

Track latency, traffic, errors, and saturation for every service boundary.

3. Correlation IDs

Thread a unique ID through all logs and spans for a single request, enabling end-to-end tracing.

4. Bounded Cardinality

Keep metric label values bounded. Unbounded labels (like user IDs) explode storage costs.

Quick Start

import structlog

structlog.configure(
    processors=[
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.JSONRenderer(),
    ],
)

logger = structlog.get_logger()
logger.info("Request processed", user_id="123", duration_ms=45)

Fundamental Patterns

Pattern 1: Structured Logging with Structlog

Configure structlog for JSON output with consistent fields.

import logging
import structlog

def configure_logging(log_level: str = "INFO") -> None:
    """Configure structured logging for the application."""
    structlog.configure(
        processors=[
            structlog.contextvars.merge_contextvars,
            structlog.processors.add_log_level,
            structlog.processors.TimeStamper(fmt="iso"),
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.processors.JSONRenderer(),
        ],
        wrapper_class=structlog.make_filtering_bound_logger(
            getattr(logging, log_level.upper())
        ),
        context_class=dict,
        logger_factory=structlog.PrintLoggerFactory(),
        cache_logger_on_first_use=True,
    )

# Initialize at application startup
configure_logging("INFO")
logger = structlog.get_logger()
Pattern 2: Consistent Log Fields

Every log entry should include standard fields for filtering and correlation.

import structlog
from contextvars import ContextVar

# Store correlation ID in context
correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")

logger = structlog.get_logger()

def process_request(request: Request) -> Response:
    """Process request with structured logging."""
    logger.info(
        "Request received",
        correlation_id=correlation_id.get(),
        method=request.method,
        path=request.path,
        user_id=request.user_id,
    )

    try:
        result = handle_request(request)
        logger.info(
            "Request completed",
            correlation_id=correlation_id.get(),
            status_code=200,
            duration_ms=elapsed,
        )
        return result
    except Exception as e:
        logger.error(
            "Request failed",
            correlation_id=correlation_id.get(),
            error_type=type(e).__name__,
            error_message=str(e),
        )
        raise
Pattern 3: Semantic Log Levels

Use log levels consistently across the application.

Level Purpose Examples
DEBUG Development diagnostics Variable values, internal state
INFO Request lifecycle, operations Request start/end, job completion
WARNING Recoverable anomalies Retry attempts, fallback used
ERROR Failures needing attention Exceptions, service unavailable
# DEBUG: Detailed internal information
logger.debug("Cache lookup", key=cache_key, hit=cache_hit)

# INFO: Normal operational events
logger.info("Order created", order_id=order.id, total=order.total)

# WARNING: Abnormal but handled situations
logger.warning(
    "Rate limit approaching",
    current_rate=950,
    limit=1000,
    reset_seconds=30,
)

# ERROR: Failures requiring investigation
logger.error(
    "Payment processing failed",
    order_id=order.id,
    error=str(e),
    payment_provider="stripe",
)

Never log expected behavior at ERROR. A user entering a wrong password is INFO, not ERROR.

Pattern 4: Correlation ID Propagation

Generate a unique ID at ingress and thread it through all operations.

from contextvars import ContextVar
import uuid
import structlog

correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")

def set_correlation_id(cid: str | None = None) -> str:
    """Set correlation ID for current context."""
    cid = cid or str(uuid.uuid4())
    correlation_id.set(cid)
    structlog.contextvars.bind_contextvars(correlation_id=cid)
    return cid

# FastAPI middleware example
from fastapi import Request

async def correlation_middleware(request: Request, call_next):
    """Middleware to set and propagate correlation ID."""
    # Use incoming header or generate new
    cid = request.headers.get("X-Correlation-ID") or str(uuid.uuid4())
    set_correlation_id(cid)

    response = await call_next(request)
    response.headers["X-Correlation-ID"] = cid
    return response

Propagate to outbound requests:

import httpx

async def call_downstream_service(endpoint: str, data: dict) -> dict:
    """Call downstream service with correlation ID."""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            endpoint,
            json=data,
            headers={"X-Correlation-ID": correlation_id.get()},
        )
        return response.json()

Detailed worked examples and patterns

Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.

Best Practices Summary

  1. Use structured logging - JSON logs with consistent fields
  2. Propagate correlation IDs - Thread through all requests and logs
  3. Track the four golden signals - Latency, traffic, errors, saturation
  4. Bound label cardinality - Never use unbounded values as metric labels
  5. Log at appropriate levels - Don't cry wolf with ERROR
  6. Include context - User ID, request ID, operation name in logs
  7. Use context managers - Consistent timing and error handling
  8. Separate concerns - Observability code shouldn't pollute business logic
  9. Test your observability - Verify logs and metrics in integration tests
  10. Set up alerts - Metrics are useless without alerting
1---
2name: python-observability
3description: Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.
4---
5 
6# Python Observability
7 
8Instrument Python applications with structured logs, metrics, and traces. When something breaks in production, you need to answer "what, where, and why" without deploying new code.
9 
10## When to Use This Skill
11 
12- Adding structured logging to applications
13- Implementing metrics collection with Prometheus
14- Setting up distributed tracing across services
15- Propagating correlation IDs through request chains
16- Debugging production issues
17- Building observability dashboards
18 
19## Core Concepts
20 
21### 1. Structured Logging
22 
23Emit logs as JSON with consistent fields for production environments. Machine-readable logs enable powerful queries and alerts. For local development, consider human-readable formats.
24 
25### 2. The Four Golden Signals
26 
27Track latency, traffic, errors, and saturation for every service boundary.
28 
29### 3. Correlation IDs
30 
31Thread a unique ID through all logs and spans for a single request, enabling end-to-end tracing.
32 
33### 4. Bounded Cardinality
34 
35Keep metric label values bounded. Unbounded labels (like user IDs) explode storage costs.
36 
37## Quick Start
38 
39```python
40import structlog
41 
42structlog.configure(
43 processors=[
44 structlog.processors.TimeStamper(fmt="iso"),
45 structlog.processors.JSONRenderer(),
46 ],
47)
48 
49logger = structlog.get_logger()
50logger.info("Request processed", user_id="123", duration_ms=45)
51```
52 
53## Fundamental Patterns
54 
55### Pattern 1: Structured Logging with Structlog
56 
57Configure structlog for JSON output with consistent fields.
58 
59```python
60import logging
61import structlog
62 
63def configure_logging(log_level: str = "INFO") -> None:
64 """Configure structured logging for the application."""
65 structlog.configure(
66 processors=[
67 structlog.contextvars.merge_contextvars,
68 structlog.processors.add_log_level,
69 structlog.processors.TimeStamper(fmt="iso"),
70 structlog.processors.StackInfoRenderer(),
71 structlog.processors.format_exc_info,
72 structlog.processors.JSONRenderer(),
73 ],
74 wrapper_class=structlog.make_filtering_bound_logger(
75 getattr(logging, log_level.upper())
76 ),
77 context_class=dict,
78 logger_factory=structlog.PrintLoggerFactory(),
79 cache_logger_on_first_use=True,
80 )
81 
82# Initialize at application startup
83configure_logging("INFO")
84logger = structlog.get_logger()
85```
86 
87### Pattern 2: Consistent Log Fields
88 
89Every log entry should include standard fields for filtering and correlation.
90 
91```python
92import structlog
93from contextvars import ContextVar
94 
95# Store correlation ID in context
96correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")
97 
98logger = structlog.get_logger()
99 
100def process_request(request: Request) -> Response:
101 """Process request with structured logging."""
102 logger.info(
103 "Request received",
104 correlation_id=correlation_id.get(),
105 method=request.method,
106 path=request.path,
107 user_id=request.user_id,
108 )
109 
110 try:
111 result = handle_request(request)
112 logger.info(
113 "Request completed",
114 correlation_id=correlation_id.get(),
115 status_code=200,
116 duration_ms=elapsed,
117 )
118 return result
119 except Exception as e:
120 logger.error(
121 "Request failed",
122 correlation_id=correlation_id.get(),
123 error_type=type(e).__name__,
124 error_message=str(e),
125 )
126 raise
127```
128 
129### Pattern 3: Semantic Log Levels
130 
131Use log levels consistently across the application.
132 
133| Level | Purpose | Examples |
134|-------|---------|----------|
135| `DEBUG` | Development diagnostics | Variable values, internal state |
136| `INFO` | Request lifecycle, operations | Request start/end, job completion |
137| `WARNING` | Recoverable anomalies | Retry attempts, fallback used |
138| `ERROR` | Failures needing attention | Exceptions, service unavailable |
139 
140```python
141# DEBUG: Detailed internal information
142logger.debug("Cache lookup", key=cache_key, hit=cache_hit)
143 
144# INFO: Normal operational events
145logger.info("Order created", order_id=order.id, total=order.total)
146 
147# WARNING: Abnormal but handled situations
148logger.warning(
149 "Rate limit approaching",
150 current_rate=950,
151 limit=1000,
152 reset_seconds=30,
153)
154 
155# ERROR: Failures requiring investigation
156logger.error(
157 "Payment processing failed",
158 order_id=order.id,
159 error=str(e),
160 payment_provider="stripe",
161)
162```
163 
164Never log expected behavior at `ERROR`. A user entering a wrong password is `INFO`, not `ERROR`.
165 
166### Pattern 4: Correlation ID Propagation
167 
168Generate a unique ID at ingress and thread it through all operations.
169 
170```python
171from contextvars import ContextVar
172import uuid
173import structlog
174 
175correlation_id: ContextVar[str] = ContextVar("correlation_id", default="")
176 
177def set_correlation_id(cid: str | None = None) -> str:
178 """Set correlation ID for current context."""
179 cid = cid or str(uuid.uuid4())
180 correlation_id.set(cid)
181 structlog.contextvars.bind_contextvars(correlation_id=cid)
182 return cid
183 
184# FastAPI middleware example
185from fastapi import Request
186 
187async def correlation_middleware(request: Request, call_next):
188 """Middleware to set and propagate correlation ID."""
189 # Use incoming header or generate new
190 cid = request.headers.get("X-Correlation-ID") or str(uuid.uuid4())
191 set_correlation_id(cid)
192 
193 response = await call_next(request)
194 response.headers["X-Correlation-ID"] = cid
195 return response
196```
197 
198Propagate to outbound requests:
199 
200```python
201import httpx
202 
203async def call_downstream_service(endpoint: str, data: dict) -> dict:
204 """Call downstream service with correlation ID."""
205 async with httpx.AsyncClient() as client:
206 response = await client.post(
207 endpoint,
208 json=data,
209 headers={"X-Correlation-ID": correlation_id.get()},
210 )
211 return response.json()
212```
213 
214## Detailed worked examples and patterns
215 
216Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
217 
218## Best Practices Summary
219 
2201. **Use structured logging** - JSON logs with consistent fields
2212. **Propagate correlation IDs** - Thread through all requests and logs
2223. **Track the four golden signals** - Latency, traffic, errors, saturation
2234. **Bound label cardinality** - Never use unbounded values as metric labels
2245. **Log at appropriate levels** - Don't cry wolf with ERROR
2256. **Include context** - User ID, request ID, operation name in logs
2267. **Use context managers** - Consistent timing and error handling
2278. **Separate concerns** - Observability code shouldn't pollute business logic
2289. **Test your observability** - Verify logs and metrics in integration tests
22910. **Set up alerts** - Metrics are useless without alerting
230 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillDiagnose why a specific ad creative is winning or losingCreative performance analysisgmmh1/claude-paid-media-skills · by gmmh1Diagnose why a specific ad creative is winning or losing using the generalized hook-hold-click-convert funnel, applicable across any platform. Triggers on 'why is this ad underperforming', 'diagnose my creative', or 'where in the funnel is this ad failing'. Platform-agnostic diagnostic framework — platform-specific versions (meta-ads-creative-analytics) apply this with platform-native metrics.New listingPromptAct as a professional full-stack developer taskedProfessional Full-Stack Developer for Network Mapping & Monitoring Applicationf/prompts.chat · by Yohanes Farly RakinaungAct as a professional full-stack developer tasked with building a web application for mapping and monitoring networks using Mikrotik Netwatch API. Implement multi-user role-based management to handle devices, monitor their status, and manage user subscriptions.New listingSkillEstablishes a project's quality bar as a written contractConstraint driven developmentaddyosmani/agent-skills · by addyosmaniEstablishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.★ 98.7k GitHub starsSkillInstruments code so production behavior is visibleObservability and instrumentationaddyosmani/agent-skills · by addyosmaniInstruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.★ 98.7k GitHub starsSkillOptimizes application performance across frontend, backendPerformance optimizationaddyosmani/agent-skills · by addyosmaniOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.★ 98.7k GitHub starsSkillDiscovers and invokes agent skillsUsing agent skillsaddyosmani/agent-skills · by addyosmaniDiscovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked.★ 98.7k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars