Reference library

Observability & SRE

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

11 matches
Observability & SRE easy

Calculate Error Rate from Log Stream in Python

Parses a mock log stream to count errors and compute the error percentage using a rolling window of recent entries.

logging regex error-rate
Python
import re
from collections import deque

def error_rate_from_log_stream(message):
    log_pattern = r'^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] (ERROR|INFO|DEBUG): (.*)$'
    recent_entries = deque(maxlen=100)
    error_count = 0
    total_count = 0

    for line in message.strip().split('\n'):
        match = re.mat…
15 0 Open
Observability & SRE easy

How to Add Metadata Attributes to a Span in Python

Create a lightweight dataclass-based Span mock that stores key-value metadata attributes for tracing or event logging.

dataclasses observability tracing
Python
from dataclasses import dataclass, field
from typing import Dict, Any

@dataclass
class Span:
    name: str
    attributes: Dict[str, Any] = field(default_factory=dict)
    
    def set_attribute(self, key: str, value: Any) -> None:
        self.attributes[key] = value
    
    def get_attribute(self, key: str) -> Any…
14 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 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 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 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 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 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

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

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.