⬢ Tutorial: Implementing Persistent Audit Logging with Postgres
This guide walks you through transitioning from a local demo setup to a centralized, persistent audit trail using hexarch-guardrails 0.4.6b1.
1. Prerequisites & Installation
Install with the postgres extra:
pip install "hexarch-guardrails[postgres]==0.4.6b1"
2. Configure the PostgresAuditStore
Unlike the default in‑memory logger, the PostgresAuditStore requires database connection details.
from hexarch_guardrails import Guardian
from hexarch_guardrails.audit import DecisionLogger, PostgresAuditStore
# 1. Initialize the persistent storage backend
store = PostgresAuditStore(
host="audit-db.internal",
database="centralized_audit",
user="service_account",
password="your_secure_password"
)
# 2. Create the logger instance
audit_logger = DecisionLogger(store)
# 3. Inject the logger into the Guardian
guardian = Guardian(
policy_file="hexarch.yaml",
audit_logger=audit_logger
)
3. Captured Metadata & Automated Context
When using PostgresAuditStore, the library captures a rich set of metadata for every decision:
- Decision IDs: Every block or allowance gets a unique UUID.
- Automated User Context: If your guarded function includes
user_id, it’s captured automatically. - Evaluation Performance: Tracks
duration_msto ensure guardrails aren’t slowing production.
4. Querying the Audit Trail for Compliance
With persistent storage, you can query history for security reviews or SOC 2 evidence:
blocked_history = audit_logger.get_blocked_operations(
timeframe="7d",
limit=50
)
for entry in blocked_history:
print(f"[{entry.timestamp}] BLOCKED: {entry.policy_id}")
print(f"Reason: {entry.reason} | User: {entry.user_id}")
5. Production Maintenance: Log Rotation
Keep your audit table healthy by cleaning old records:
# Run as a daily maintenance task
deleted_count = audit_logger.cleanup_old_records(days=90)
print(f"Archived {deleted_count} old audit entries.")
Result: You now have a centralized, immutable audit trail that proves guardrails are working—and a clean path to SOC2/HIPAA evidence.