Reference library

Observability & SRE

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

8 matches
Observability & SRE easy

Generate Synthetic SRE Metrics and Calculate Availability in Python

Create realistic service metrics with random latency, error rate, and request counts, then compute availability and summarize the stream for SLO checks.

sre synthetic-data metrics
Python
from datetime import datetime, timedelta
import random

def generate_service_metrics(service_name: str, minutes: int = 30) -> list[dict]:
    """Generate synthetic SRE metrics for a service across recent minutes."""
    metrics = []
    now = datetime.now()
    
    for i in range(minutes):
        timestamp = now - t…
14 0 Open
Observability & SRE easy

How to Calculate Apdex Score from Latency Data in Python

Generate simulated latency samples and compute the Apdex score to gauge user satisfaction with an application's performance.

apdex latency observability
Python
import random
import statistics

def generate_latencies(count=100, base=100, stddev=30):
    return [max(0, random.gauss(base, stddev)) for _ in range(count)]

def apdex(latencies, threshold=200):
    satisfied = sum(1 for lat in latencies if lat < threshold)
    tolerating = sum(1 for lat in latencies if lat >= thres…
15 0 Open
Observability & SRE easy

How to Check Service Readiness Dependencies in Python

This code simulates a readiness check for external dependencies (database, cache, queue) with mock availability data and reports readiness status.

readiness dependencies health-check
Python
import sys
from datetime import datetime


def check_dependencies(config):
    results = []
    for dep, required in config.items():
        available = mock_availability(dep)
        status = "READY" if available >= required else "NOT READY"
        results.append((dep, available, required, status))
    return result…
11 0 Open
Observability & SRE easy

How to Compute SRE Metrics Like Error Rate and Availability in Python

Tracks log events in a sliding time window and calculates error rate per second and availability percentage using an easy-to-follow class.

observability sre metrics
Python
from collections import deque
from datetime import datetime, timedelta
from typing import Dict, Deque


class LogMetrics:
    """Simple observability helper to track log events and calculate SRE metrics."""

    def __init__(self, window_seconds: int = 60):
        self.window_seconds = window_seconds
        self.eve…
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 mock Prometheus alert rule thresholds in Python

Simulate a Prometheus alert rule with a configurable threshold and duration window, firing only when the metric exceeds the threshold long enough.

prometheus alerting sre
Python
import time
import random


class MetricsStore:
    def __init__(self):
        self.metrics = {}

    def set_metric(self, name, value, labels=None):
        key = (name, tuple(sorted((labels or {}).items())))
        self.metrics[key] = value

    def get_metric(self, name, labels=None):
        key = (name, tuple(s…
14 0 Open
Observability & SRE easy

How to mock SLI availability success ratio in Python

Simulate request outcomes with deterministic randomness and compute the SLI availability success ratio to check if a target is met.

sli availability monitoring
Python
import random
from collections import defaultdict

def mock_availability(num_requests=1000, target_ratio=0.995):
    """
    Simulate request outcomes and compute the SLI availability success ratio.
    
    Args:
        num_requests: Total number of requests to simulate
        target_ratio: Target availability rati…
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.