Reference library

Observability & SRE

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

3 matches
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 Generate and Propagate W3C Trace Context Headers in Python

Generate and propagate W3C traceparent and tracestate headers for distributed tracing in Python, with mock service headers.

observability tracing w3c
Python
import uuid


def generate_w3c_traceparent(trace_id=None, parent_id=None, flags="01"):
    if trace_id is None:
        trace_id = uuid.uuid4().hex[:32]
    if parent_id is None:
        parent_id = uuid.uuid4().hex[:16]
    return f"00-{trace_id}-{parent_id}-{flags}"


def create_mock_headers(service_name, trace_id=N…
12 0 Open
Observability & SRE easy

How to Simulate Trace Sampling Head in Python

Simulate head-based probabilistic trace sampling on mock trace data with a configurable sample rate and optional seed for reproducibility.

tracing sampling observability
Python
import random

def trace_sampling_head(mock_traces, sample_rate=0.5, seed=None):
    """Simulate probabilistic trace sampling (head-based) on mock data.
    
    Args:
        mock_traces: list of trace dictionaries with a unique 'trace_id'
        sample_rate: float 0.0-1.0, probability of keeping a trace
        see…
12 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.