Reference library

Observability & SRE

Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.

8 matches
Observability & SRE easy

Generate Mock CPU and Memory Metrics in Python

Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.

mock metrics monitoring
Python
import time
import random


def mock_host_metrics():
    """Generate mock CPU and memory metrics for a host."""
    cpu_percent = round(random.uniform(10.0, 95.0), 1)
    memory_percent = round(random.uniform(20.0, 90.0), 1)
    memory_used_mb = round(random.uniform(512, 8192), 1)

    return {
        "timestamp": in…
15 0 Open
Observability & SRE medium

How to Build a Burn Rate Alert with Multiple Time Windows in Python

Track token consumption and trigger alerts when the burn rate exceeds a threshold across multiple time windows using deque and time-based sliding windows.

burn-rate alerts time-windows
Python
import time
from collections import deque

class BurnRateAlert:
    def __init__(self, windows_seconds=(60, 300, 900), threshold_rate=0.8):
        self.windows = {w: deque() for w in windows_seconds}
        self.threshold_rate = threshold_rate
        self.previous_tokens = None

    def record_sample(self, current_…
16 0 Open
Observability & SRE easy

How to Build a Consumer Lag Gauge in Python

Simulate Kafka consumer lag with a Python class that tracks lag over time and reports health and averages.

consumer-lag kafka monitoring
Python
import time
import random
from collections import deque


class ConsumerLagGauge:
    """Mock consumer lag gauge measuring how far behind a consumer is."""

    def __init__(self, producer_rate=10, consumer_rate=7, initial_lag=0):
        self.producer_rate = producer_rate
        self.consumer_rate = consumer_rate
  …
13 0 Open
Observability & SRE easy

How to Build a Metrics Counter with Increment and Snapshot in Python

A simple dict-backed MetricsCounter class that increments named counters and returns a snapshot of the current values.

metrics counter observability
Python
class MetricsCounter:
    def __init__(self):
        self._metrics = {}

    def increment(self, key, delta=1):
        self._metrics[key] = self._metrics.get(key, 0) + delta

    def snapshot(self):
        return dict(self._metrics)


if __name__ == "__main__":
    counter = MetricsCounter()
    counter.increment("…
13 0 Open
Observability & SRE medium

How to Build a Python Latency Histogram with Mock Buckets

This code implements a mock latency histogram that records request durations into configurable buckets and outputs counts, total, and average latency.

histogram latency metrics
Python
import time
import random
from collections import Counter


class LatencyHistogram:
    def __init__(self, buckets):
        self.buckets = sorted(buckets)
        self.counts = Counter()
        self.total = 0
        self.sum_latency = 0

    def record(self, latency_ms):
        for i, boundary in enumerate(self.bu…
13 0 Open
Observability & SRE medium

How to Build an HTTP Server Request Duration Histogram in Python

Create a small HTTP server that times each GET request, buckets the duration, and prints a histogram on shutdown.

http.server histogram performance
Python
import time
import random
from collections import Counter
from http.server import HTTPServer, BaseHTTPRequestHandler


class HistogramHandler(BaseHTTPRequestHandler):
    response_times = Counter()

    def do_GET(self):
        start = time.perf_counter()
        time.sleep(random.uniform(0.001, 0.1))
        duratio…
13 0 Open
Observability & SRE easy

How to Redact Secrets from Log Messages in Python

Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.

redaction logging secrets
Python
class RedactingFormatter:
    def __init__(self, secrets):
        self.secrets = secrets

    def redact(self, message):
        for secret in self.secrets:
            message = message.replace(secret, "[REDACTED]")
        return message

    def format(self, record):
        message = record["message"]
        ret…
12 0 Open
Observability & SRE medium

Summary Quantile Mock Sketch in Python

Build a memory-efficient sketch that stores sorted bins of data points to answer approximate quantile queries like median without keeping all values in memory.

quantile sketch statistics
Python
import random
import statistics
from collections import Counter

class SummaryQuantileSketch:
    """
    A simple sketch that stores a fixed-size summary of data (min, max, deciles)
    using sorted bins, then answers approximate quantile queries.
    """
    def __init__(self, bins=10):
        self.bins = bins
    …
13 0 Open

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.