Observability & SRE
Structured logging, metrics, tracing, health checks, and SLO-friendly instrumentation.
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.
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…
Generate Mock CPU and Memory Metrics in Python
Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.
import time
import random
def mock_host_metrics():
"""Generate mock CPU and memory metrics for a host."""
cpu_percent = round(random.uniform(10.0, 95.0), 1)
memory_percent = round(random.uniform(20.0, 90.0), 1)
memory_used_mb = round(random.uniform(512, 8192), 1)
return {
"timestamp": in…
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.
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…
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.
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…
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.
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…
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.