Reference library

Observability & SRE

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

3 matches
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 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

Rotate Log Files by Size in Python

A mock log rotation script that renames log files exceeding a size threshold, appending numbered backups.

log-rotation pathlib file-management
Python
import os
from pathlib import Path

def rotate_logs(directory: str, max_size: int = 100) -> None:
    """Rotate log files that exceed max_size bytes."""
    log_dir = Path(directory)
    for log_file in sorted(log_dir.glob("*.log"), key=lambda p: str(p)):
        if log_file.stat().st_size > max_size:
            for …
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.