Engineer a repository for audit logging using append-only event streams and retention…
- User
Engineer a repository for audit logging using append-only event streams and retention policies.
Assistant
Engineer a repository for audit logging using append-only event streams and retention policies.
The user wants an "engineered repository" for audit logging. Key features requested:
I need to provide a solution that covers:
Design Choice: Segmented Logs The standard industry pattern for append-only logs (like Kafka, UNIX logs) is segmented files.
audit_001.log (open for writing).audit_000.log (immutable).Refining the Retention Policy:
Implementation Details (Python):
AuditEvent: A dataclass (JSON serializable).AuditLogRepository: The main class.
append(event): Serializes and writes to the current active segment. Checks if segment needs rotation.rotate(): Closes current file, opens new one.enforce_retention(): Checks file list against policy, deletes old ones.Let's add a twist/robustness: Indexing.
Pure append-only is fast for writes, slow for reads. For an "audit log," you often need to search by entity_id or event_type. A full index might violate strict "append-only" if stored in the same stream, but a side-car index is acceptable. However, for a basic "repository" example, I should stick to the core requirement: the stream and retention. I will mention indexing as an optimization.
Structure of the response:
Config: Settings for retention.AuditEvent: Pydantic model or dataclass.SegmentedLog: Handles the low-level file I/O.RetentionManager: The cleanup logic.Drafting the Python Code:
./audit_logs/event_timestamp_uuid.jsonl (JSON Lines format is best for logs).max_age_days, max_size_mb.Self-Correction during thought process: Should I use a database? The prompt asks to engineer a repository. Using SQL INSERT is technically append-only, but file-based segmented logs demonstrate the concept better and are often more performant for pure logging than a random-access SQL DB without specific tuning (like TimescaleDB). I will implement a file-based JSON Lines approach as it's the textbook definition of an append-only log system.
Key Logic for Retention:
Code Sketch:
class AuditLog:
def __init__(self, config):
self.config = config
self.current_file = open(...)
def log(self, event):
# serialize
# write
# check size -> rotate()
def rotate(self):
# close current
# open new
def apply_retention(self):
# list files
# sort by time
# remove oldest if sum(size) > max or oldest_time < threshold
Let's refine the apply_retention. It needs to be separate from the write path (usually runs in a background thread or cron), but for a simple repo class, an explicit call is fine.
Final Polish:
Ensure the code is clean, type-hinted, and robust (using uuid, datetime). Add docstrings. Explain why we do it this way (immutability, compaction).
Let's write the response. This solution implements a robust Audit Log Repository in Python. It uses the Segmented Log pattern, common in distributed systems (like Kafka or Cassandra), to handle append-only streams efficiently. It separates the "Active" log from "Archived" segments to enforce retention policies without complex random-access deletes.
update or delete methods for specific records.Instead of writing to a single monolithic file audit.log, we write to an active.log. When this file hits a threshold (segment_size_kb), it is moved (renamed) to the archive/ folder. This makes retention extremely fast: deleting a 1GB log file takes milliseconds, whereas pruning lines from inside a file requires rewriting the entire file.
The logs are stored as newline-delimited JSON (jsonl).
A threading.RLock is used to ensure that if multiple threads try to append events simultaneously, the file writes don't interleave and corrupt the lines.
now - timestamp > retention_days, the file is deleted.total > max_size, it deletes the oldest files first until it fits._rotate_segment to gzip the file before moving it to archive. This saves significant disk space.actor quickly, maintain a separate index file (e.g., a SQLite DB or a hash map) that maps actor_id -> [filenames]._rotate_segment method, add logic to upload the closed segment to AWS S3 or Azure Blob Storage for long-term cold storage, then delete the local copy.import json
import os
import time
import threading
from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from typing import List, Optional, Dict, Any, Iterator
from pathlib import Path
import uuid
# ==========================================
# 1. Domain Model
# ==========================================
@dataclass(frozen=True)
class AuditEvent:
"""
Immutable record of an action.
"""
event_id: str
timestamp: str # ISO 8601 UTC
action: str
actor: str
resource: str
metadata: Dict[str, Any]
@classmethod
def create(cls, action: str, actor: str, resource: str, metadata: Optional[Dict] = None):
return cls(
event_id=str(uuid.uuid4()),
timestamp=datetime.now(timezone.utc).isoformat(),
action=action,
actor=actor,
resource=resource,
metadata=metadata or {}
)
def to_json(self) -> str:
return json.dumps(asdict(self))
@staticmethod
def from_json(data: str) -> 'AuditEvent':
return AuditEvent(**json.loads(data))
# ==========================================
# 2. Configuration
# ==========================================
@dataclass
class RetentionPolicy:
max_size_mb: int = 100 # Max total size of all segments
retention_days: int = 30 # Delete segments older than X days
segment_size_kb: int = 1024 # Rotate active file after ~1MB
# ==========================================
# 3. Repository Implementation
# ==========================================
class AuditLogRepository:
def __init__(self, base_dir: str, policy: RetentionPolicy = None):
self.base_path = Path(base_dir)
self.policy = policy or RetentionPolicy()
self.active_segment_path = self.base_path / "active.log"
self.segments_dir = self.base_path / "archive"
# State
self._lock = threading.RLock() # Ensures thread safety for writes
self._current_size = 0
self._ensure_structure()
def _ensure_structure(self):
self.base_path.mkdir(parents=True, exist_ok=True)
self.segments_dir.mkdir(parents=True, exist_ok=True)
if self.active_segment_path.exists():
self._current_size = self.active_segment_path.stat().st_size
# --- Write Path (Append-Only) ---
def append(self, event: AuditEvent):
"""
Appends an event to the active log segment.
If segment exceeds policy size, it is rotated.
"""
with self._lock:
line = event.to_json() + "\n"
line_bytes = line.encode('utf-8')
# Rotate if necessary
if self._current_size + len(line_bytes) > (self.policy.segment_size_kb * 1024):
self._rotate_segment()
with open(self.active_segment_path, 'a', encoding='utf-8') as f:
f.write(line)
self._current_size += len(line_bytes)
def _rotate_segment(self):
"""
Moves the active log to the archive folder with a timestamped name
and creates a new active log.
"""
if not self.active_segment_path.exists():
return
# e.g., archive/events_1698240123.log
timestamp = int(time.time())
archive_name = f"events_{timestamp}.log"
target_path = self.segments_dir / archive_name
# Atomic rename operation
os.rename(self.active_segment_path, target_path)
self._current_size = 0
print(f"[System] Rotated log to {archive_name}")
# --- Read Path (Replay) ---
def read_all(self) -> Iterator[AuditEvent]:
"""
Generator to stream all events (Active + Archived) sequentially.
Oldest archived segments are read first.
"""
# 1. Read Archived Segments (Oldest first)
segments = sorted(self.segments_dir.glob("*.log"))
for seg in segments:
with open(seg, 'r', encoding='utf-8') as f:
for line in f:
try:
yield AuditEvent.from_json(line.strip())
except json.JSONDecodeError:
continue
# 2. Read Active Segment
if self.active_segment_path.exists():
with open(self.active_segment_path, 'r', encoding='utf-8') as f:
for line in f:
try:
yield AuditEvent.from_json(line.strip())
except json.JSONDecodeError:
continue
# --- Retention Path (Janitor) ---
def enforce_retention(self):
"""
Deletes segments based on time and size constraints.
Should be run periodically (e.g., via cron or background thread).
"""
with self._lock:
self._enforce_time_retention()
self._enforce_size_retention()
def _enforce_time_retention(self):
now = time.time()
cutoff = now - (self.policy.retention_days * 86400)
for seg in self.segments_dir.glob("*.log"):
# Extract timestamp from filename: events_1698240123.log
try:
ts = int(seg.stem.split('_')[1])
if ts < cutoff:
os.remove(seg)
print(f"[Retention] Deleted expired segment: {seg.name}")
except (IndexError, ValueError):
continue
def _enforce_size_retention(self):
"""
If total storage exceeds max_size_mb, delete the oldest segments
until we are under the limit.
"""
max_bytes = self.policy.max_size_mb * 1024 * 1024
# Get all segments sorted by name (which implies time sort)
segments = sorted(self.segments_dir.glob("*.log"))
# Calculate total size of archived segments
total_size = sum(f.stat().st_size for f in segments)
# Add active segment size
if self.active_segment_path.exists():
total_size += self.active_segment_path.stat().st_size
# Delete oldest until under limit
for seg in segments:
if total_size <= max_bytes:
break
file_size = seg.stat().st_size
try:
os.remove(seg)
total_size -= file_size
print(f"[Retention] Deleted segment due to size cap: {seg.name}")
except OSError:
pass
# ==========================================
# 4. Usage Example
# ==========================================
if __name__ == "__main__":
# Setup
config = RetentionPolicy(
max_size_mb=10,
retention_days=7,
segment_size_kb=1 # Set small for demo to force rotation
)
repo = AuditLogRepository("./audit_logs", policy=config)
print("--- Writing Events ---")
# 1. Generate enough data to trigger rotation
for i in range(50):
event = AuditEvent.create(
action="USER_LOGIN",
actor=f"user_{i}",
resource="/dashboard",
metadata={"ip": "127.0.0.1", "status": "success"}
)
repo.append(event)
# Force a rotation manually to demonstrate archiving
repo._rotate_segment()
# Add more data to active log
repo.append(AuditEvent.create("SYSTEM_START", "system", "server", None))
print("\n--- Reading Events (Streaming) ---")
count = 0
for evt in repo.read_all():
count += 1
# print(f"Event: {evt.action} by {evt.actor} at {evt.timestamp}")
print(f"Total events read: {count}")
print("\n--- Enforcing Retention ---")
repo.enforce_retention()