Reference library

Observability & SRE

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

13 matches
Observability & SRE easy

Check if a Timestamp Falls in a Daily Maintenance Window in Python

A small Python function that returns True when a datetime falls inside a daily maintenance window, and a demo printing yes/no for sample timestamps.

maintenance datetime scheduling
Python
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo


def in_maintenance_window(now: datetime, start_hour: int = 2, duration_hours: int = 4) -> bool:
    """Return True if 'now' falls inside the daily maintenance window."""
    day_start = now.replace(hour=start_hour, minute=0, second=0, microsecond…
15 0 Open
Observability & SRE easy

Generate Synthetic CPU Utilization Metrics in Python

Creates realistic time-series CPU utilization samples with timestamps, noise, and output as structured JSON for observability demos and testing.

observability metrics time-series
Python
from datetime import datetime, timedelta
import random
import json


def generate_metric_samples(base_value, noise, count=60, interval_minutes=1):
    """Generate realistic CPU utilization samples for a given time window."""
    timestamps = []
    values = []

    now = datetime.utcnow()
    start_time = now - timede…
14 0 Open
Observability & SRE easy

How to Build a Consumer Lag Gauge in Python

Simulate Kafka consumer lag with a Python class that tracks lag over time and reports health and averages.

consumer-lag kafka monitoring
Python
import time
import random
from collections import deque


class ConsumerLagGauge:
    """Mock consumer lag gauge measuring how far behind a consumer is."""

    def __init__(self, producer_rate=10, consumer_rate=7, initial_lag=0):
        self.producer_rate = producer_rate
        self.consumer_rate = consumer_rate
  …
13 0 Open
Observability & SRE easy

How to Calculate SLO Error Budget in Python

Simulate an SLO error budget by computing allowed downtime from a target availability percentage and mocking monthly incidents.

slo error-budget monitoring
Python
```python
import random


def calculate_error_budget(total_seconds: int, target_availability: float) -> float:
    return (1.0 - target_availability) * total_seconds


def simulate_monthly_availability(seconds_in_month: int, budget_seconds: float) -> float:
    # Mock: randomly consume a fraction of the error budget i…
15 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 Create a Deep Health Check Database in Python

Setup a SQLite-backed health check database, insert mock data with response times and statuses, and generate a report ordered by most recent check.

sqlite health-check database
Python
import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

DB_PATH = Path("deep_health_check.db")


def setup_database():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS health_checks (
            id INTEGER PRIMARY KEY AU…
14 0 Open
Observability & SRE easy

How to Do Structured JSON Line Logging in Python

Create a simple JSON-lines logger that writes one JSON object per line to stdout with timestamp, level, message, and custom context fields.

logging json observability
Python
import json
import sys
from datetime import datetime

class JsonLineLogger:
    def __init__(self, stream=sys.stdout):
        self.stream = stream

    def log(self, level, message, **context):
        record = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": level,
            "me…
15 0 Open
Observability & SRE easy

How to Do Structured JSON Logging in Python

Create a custom logging formatter that outputs each log entry as a single JSON line with timestamp, level, logger name, and message.

logging json observability
Python
import json
import logging
from datetime import datetime


class JsonFormatter(logging.Formatter):
    def format(self, record):
        log_entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": record.levelname,
            "logger": record.name,
            "message": record.ge…
14 0 Open
Observability & SRE easy

How to Mock HTTP Client Latency in Python

Simulate outbound HTTP request latency with configurable ranges to test timeouts, retries, and SLO monitoring without external services.

latency mocking http-client
Python
import time
import random

def mock_latency(host: str, min_ms: int = 100, max_ms: int = 500) -> dict:
    """Simulate an outbound HTTP request with mock latency."""
    latency_ms = random.randint(min_ms, max_ms)
    start = time.perf_counter()
    time.sleep(latency_ms / 1000)
    elapsed_ms = (time.perf_counter() - …
14 0 Open
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 Parse Log Lines with Regex in Python

Extracts timestamp, log level, service name, and message from a log line using compiled regex named groups.

regex logging parsing
Python
import re

LOG_PATTERN = re.compile(
    r'^(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) '
    r'\[(?P<level>\w+)\] '
    r'\((?P<service>[^)]+)\) '
    r'(?P<message>.*)$'
)

def parse_log_line(line: str) -> dict:
    match = LOG_PATTERN.match(line)
    if not match:
        return {"error": "invalid log format…
14 0 Open
Observability & SRE easy

How to Simulate a Queue Depth Gauge in Python

Simulate a queue depth over time using a random enqueue/dequeue process, returning depth values that can be used for monitoring or testing dashboards.

queue simulation monitoring
Python
import collections
import random
import time


def simulate_queue_depth(max_depth=10, steps=20):
    queue = collections.deque()
    depth_history = []

    for _ in range(steps):
        # Randomly enqueue or dequeue
        if random.random() < 0.6 and len(queue) < max_depth:
            queue.append("task")
       …
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

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.