Reference library

Observability & SRE

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

36 matches
Observability & SRE easy

How to Model Span Events in Python

Define a Span class with timestamped milestone events and a completion marker to track operation lifecycle.

observability dataclasses tracing
Python
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import List


class SpanStatus(Enum):
    STARTED = "started"
    COMPLETED = "completed"


@dataclass
class SpanEvent:
    name: str
    timestamp: float = field(default_factory=time.time)
    attributes: dict = field(default_facto…
14 0 Open
Observability & SRE easy

How to Process System Metrics (RSS, CPU) in Python

Simulate and aggregate RSS and CPU system metrics to compute averages and maximums for monitoring dashboards.

metrics rss cpu
Python
import random
import time
from collections import namedtuple

Metric = namedtuple("Metric", ["name", "value", "unit"])


def generate_metrics(num_metrics: int = 5) -> list:
    """Simulate a batch of system metrics."""
    metrics = []
    for i in range(num_metrics):
        rss = random.randint(50, 500)  # MB
      …
12 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 easy

How to Route Alerts by Severity in Python

Map alert severity levels to routing targets and simulate dispatching alerts to on-call pages, email, Slack, or logs.

observability alerts routing
Python
def main():
    # Severity levels with corresponding alert routing targets
    routing_map = {
        "critical": "call_page",
        "high": "call_page",
        "medium": "email_team",
        "low": "slack_channel",
        "info": "log_only"
    }

    # Simulated alerts with severity
    alerts = [
        {"na…
12 0 Open
Observability & SRE easy

How to Ship Logs to an Aggregator Endpoint in Python

Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.

logging requests json
Python
import json
import requests
from datetime import datetime, timezone

LOG_ENTRIES = [
    {"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
    {"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
    {"timestamp": "2024-01-15T10:00:10Z", "level": "E…
13 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
Observability & SRE medium

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.

cache lru hit-ratio
Python
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
     …
13 0 Open
Observability & SRE easy

How to Use Log Levels DEBUG INFO WARNING ERROR in Python

Demonstrates Python's logging levels (DEBUG, INFO, WARNING, ERROR) with basicConfig and a logger, showing how severity filtering controls output.

logging log-levels observability
Python
import logging

# Configure a mock logger to demonstrate log levels
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logger = logging.getLogger("mock_logger")

# Simulate events at each severity level
logger.debug("Detailed diagnostic info")
logger.info("General system operation")
logger.w…
13 0 Open
Observability & SRE easy

Mock Health Endpoint Liveness Check in Python

Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.

health check mock observability
Python
import time
import random


def liveness_check(service_name: str, failure_rate: float = 0.1) -> dict:
    """Mock health check that returns liveness status with a configurable failure rate."""
    healthy = random.random() > failure_rate
    response = {
        "service": service_name,
        "status": "alive" if he…
16 0 Open
Observability & SRE easy

Mocking a Metrics Gauge's set_value Method in Python

Demonstrates using unittest.mock.Mock with wraps to intercept a gauge's set_value call while verifying arguments and preserving real behavior.

unittest mocking metrics
Python
from unittest.mock import Mock

class MetricsGauge:
    def __init__(self, name):
        self.name = name
        self.value = 0.0

    def set_value(self, new_value):
        self.value = float(new_value)
        return self.value

# Usage demonstration with a mock
gauge = MetricsGauge("cpu_usage")
gauge_mock = Mock…
13 0 Open
Observability & SRE easy

Python Observability Data Helper for Beginners

A beginner-friendly Python helper to log events, record metrics, summarize observability data, and export it as JSON.

observability logging metrics
Python
import json
from datetime import datetime
from collections import defaultdict


class ObservabilityDataHelper:
    """Helper for exploring basic observability data patterns."""

    def __init__(self):
        self.events = []
        self.metrics = defaultdict(list)

    def log_event(self, service, level, message):
…
14 0 Open
Observability & SRE easy

Track Success Rates and Latency in Python: SRE Metrics Helper

A beginner-friendly Python class to record request outcomes and latencies, then report success rate, average latency, and p99.

sre metrics latency
Python
import random
import time
from collections import defaultdict


class MetricsTracker:
    """Simple helper to track success rates and latencies for SRE beginners."""

    def __init__(self):
        self.successes = 0
        self.failures = 0
        self.latencies = []

    def record(self, success, latency_ms):
   …
14 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.