Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
Adding a Correlation ID to Log Context in Python
Injects a correlation ID into the logging context using a context manager and a custom log record factory so every log line includes the ID.
import logging
import uuid
from contextlib import contextmanager
logging.basicConfig(level=logging.INFO, format='%(levelname)s | %(correlation_id)s | %(message)s')
@contextmanager
def correlation_id_context(correlation_id):
"""Temporarily inject a correlation_id into the logging context."""
extra = {'correl…
Export Metrics with OTLP Mock in Python
Simulates system metric collection and exports them as an OTLP-like JSON payload using only Python's standard library.
from dataclasses import dataclass, asdict
import json
import random
import time
@dataclass
class Metric:
name: str
value: float
timestamp: int
unit: str = "1"
def collect_system_metrics() -> list[Metric]:
"""Mock metric collection for OTLP export simulation."""
now = int(time.time())
re…
How to Create a Mock OpenTelemetry Trace in Python
Create a mock OpenTelemetry trace in memory to test span creation, attributes, and parent-child relationships without exporting to a backend.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def create_mock_trace():
tracer_provider = TracerProvider()
span_exporter =…
How to Create a StatsD UDP Metric Mock Server in Python
Run a lightweight mock UDP server that captures StatsD metrics over a short window for local testing.
import socket
import threading
import time
def start_mock_statsd_server(host="127.0.0.1", port=8125, timeout=3):
"""Run a mock StatsD UDP server that captures metrics for a short window."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
sock.settimeout(timeout)
me…
How to Create a TCP DNS Mock Server in Python
This code creates a mock TCP DNS server that listens on a specified port, accepts probe connections, and returns a fixed DNS response header to simulate a live DNS service for testing and observability.
import socket
import threading
def handle_client(client_socket, address):
print(f"[+] Connection from {address}")
try:
while True:
data = client_socket.recv(1024)
if not data:
break
print(f"[*] Received {len(data)} bytes (TCP DNS probe)")
…
How to Group Alerts by Time Window in Python
Group alert occurrences that fall within a sliding time window per alert key, reducing noise and summarizing bursts into single events.
from collections import defaultdict
from datetime import datetime, timedelta
def group_alerts(alerts, window_minutes=10):
"""Group alerts that occur within the same time window."""
alerts_by_key = defaultdict(list)
for alert in alerts:
key = alert["key"]
timestamp = alert["timestamp"]…
How to Track Cache Hit Ratio in Python
Simulate an LRU cache with hit/miss tracking and compute a real-time hit ratio from random access patterns.
import random
import time
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
self.hits = 0
self.misses = 0
def get(self, key):
if key in self.cache:
self.hits += 1
…
Browse by section
Each section groups closely related Python snippets.
Observability & SRE — Python code examples
What you will find here
This page collects observability & sre snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.