Reference library

Observability & SRE

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

5 matches
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 medium

How to Check Uptime with a Synthetic HTTP Mock in Python

Run a mock HTTP server locally and probe it with urllib to measure synthetic uptime and response times, perfect for testing monitoring logic without external dependencies.

uptime http-server monitoring
Python
import http.server
import threading
import time
import urllib.request


class MockHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/health":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
   …
14 0 Open
Observability & SRE medium

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.

statsd udp sockets
Python
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…
13 0 Open
Observability & SRE medium

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.

socket dns tcp
Python
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)")
          …
16 0 Open
Observability & SRE easy

How to Mock an OTLP HTTP Endpoint in Python

This code implements a lightweight HTTP server that accepts OTLP/HTTP trace exports, stores spans by trace ID, and exposes them via a simple GET endpoint for debugging.

otlp http mock
Python
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from collections import defaultdict

class TraceHandler(BaseHTTPRequestHandler):
    traces = defaultdict(list)

    def do_POST(self):
        if self.path == "/v1/traces":
            length = int(self.headers.get("Content-Length", 0))
 …
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.