Skip to main content

WLKNS LABS structured logging module with 4 separated worlds, privacy redaction, and tamper-evident audit chains.

Project description

WLKNS LABS circuit-logging

Ein wiederverwendbares Python-Logging-Modul mit vier getrennten Welten, strukturiertem JSON-Output und automatischer Redaktion sensibler Daten.

Features

  • 4 separate Logger-Welten: app, audit, security, analytics
  • Strukturierte JSON-Logs — kein parsen von Textwürsten nötig
  • Automatische Privacy-Redaktionpassword, token, api_key, etc. werden automatisch auf [REDACTED] gesetzt
  • Append-Only Integritätskette — manipulationsgeschützte Audit-/Security-Logs mit verketteten SHA-256-Hashes
  • IP-Anonymisierung — täglich wechselnder Salt für GDPR-konforme Hashes (Cross-Day-Tracking unmöglich)
  • Datei-Rotation für Application- und Analytics-Logs (täglich, mit Aufbewahrung)
  • OpenTelemetry-Integration — optional Logs an OTLP-Backends exportieren
  • Service-Metadatenservice_name, service_version, environment in jedem Event
  • Stdlib-kompatibel — nutzt logging mit extra={...} für zusätzliche Felder

Schnellstart

from circuit_logging import LogConfig, WLKNSLogger

cfg = LogConfig(
    service_name="billing-api",
    service_version="2.1.0",
    environment="production",
)

log = WLKNSLogger(cfg)

# 1. Application Logs — für Entwickler und Betrieb
log.app.info("Payment processed", extra={"request_id": "abc-123"})

# 2. Audit Logs — der Tresorbereich
log.audit.info("User role changed", extra={"user_id_pseudonymized": "u-42"})

# 3. Security Logs — verdächtige Muster
log.security.warning("Suspicious login pattern", extra={"ip_hash": "10.0.0.x"})

# 4. Analytics — Produktnutzung
log.analytics.info("Feature X used", extra={"event_type": "feature_usage"})

JSON Output

Jede Log-Zeile ist ein JSON-Objekt:

{
  "timestamp": "2025-05-31 12:34:56,789",
  "service_name": "billing-api",
  "service_version": "2.1.0",
  "environment": "production",
  "severity": "INFO",
  "logger": "wlkns.app",
  "message": "Payment processed",
  "request_id": "abc-123"
}

Privacy / Datenschutz

Sensible Felder werden automatisch rekursiv ausgefiltert:

log.app.info("Login attempt", extra={
    "username": "alice",
    "password": "secret123",      # → [REDACTED]
    "token": "abc",                # → [REDACTED]
    "nested": {"api_key": "xyz"},  # → [REDACTED]
})

Betroffene Keys (partial match, case-insensitive): password, token, api_key, apikey, api-key, secret, authorization, auth, credit_card, ssn, private_key, access_token, refresh_token, passwd, pwd.

IP-Anonymisierung (täglich wechselnder Salt)

Besser als Pseudonymisierung: Derselbe IP liefert an unterschiedlichen Tagen unterschiedliche Hashes. Cross-Day-Tracking wird unmöglich, Same-Day-Analyse (z. B. Brute-Force-Erkennung) bleibt möglich.

from circuit_logging import DailySalt, anonymize_ip
from datetime import date

ds = DailySalt(master_secret=b"ein-geheimer-schlüssel")
salt = ds.salt_for(date.today())

anonymized = anonymize_ip("192.168.1.1", salt)
# z. B. "a3f7c2e9d8b1a4f6"

Die 4 Welten

Welt Zweck Beispiele
log.app Betrieb, Debugging, API-Calls Fehler, Warnungen, Performance
log.audit Manipulationsgeschützte Audit-Trail Login, Rollenänderung, Löschung
log.security Sicherheitsereignisse Brute-force, unautorisierter Zugriff
log.analytics Produkt-Telemetry Feature-Nutzung, Conversion, Churn

Jede Welt ist ein eigener logging.Logger mit eigenem Namen (wlkns.app, wlkns.audit, ...). So lassen sie sich getrennt filtern, rotieren oder an verschiedene Backends schicken.

Append-Only Integritätskette

Audit- und Security-Logs können in manipulationsgeschützte Dateien geschrieben werden. Jede Zeile enthält einen Hash, der sich auf die vorherige Zeile stützt:

log = WLKNSLogger(
    cfg,
    audit_file="/var/log/wlkns/audit.jsonl",
    security_file="/var/log/wlkns/security.jsonl",
)

Beispiel-Ausgabe (zweite Zeile verweist auf Hash der ersten):

{"message": "Login success", "_integrity_prev": "", "_integrity_hash": "abc123..."}
{"message": "Role changed", "_integrity_prev": "abc123...", "_integrity_hash": "def456..."}

Verifikation: Ein einfaches Skript liest die Datei Zeile für Zeile und prüft, ob jeder _integrity_prev mit dem _integrity_hash der Vorgängerzeile übereinstimmt. Abweichung = Manipulation.

Integrität prüfen (CLI)

python3 scripts/verify_audit.py /var/log/wlkns/audit.jsonl
# VERDICT: 42 line(s) — chain is INTACT

Oder programmatisch:

from circuit_logging import check_integrity

issues, total = check_integrity("/var/log/wlkns/audit.jsonl")
if issues:
    print(f"Chain broken at lines: {[i.line_number for i in issues]}")
else:
    print(f"All {total} lines intact.")

Log-Rotation (App & Analytics)

Audit und Security dürfen nicht rotiert werden — die Integritätskette würde brechen. Für app und analytics steht ein täglicher Rotations-Handler bereit:

from circuit_logging import RotatingJSONHandler, LogConfig

cfg = LogConfig("billing-api", "2.1.0", "production")
handler = RotatingJSONHandler(
    "/var/log/wlkns/app.jsonl",
    config=cfg,
    when="midnight",
    backup_count=30,
)
log.app.addHandler(handler)

OpenTelemetry (optional)

Für SaaS-Umgebungen kannst du Logs zusätzlich an ein OTLP-Backend schicken (Grafana, Datadog, etc.):

python3 -m pip install "circuit-logging[otel]"
from circuit_logging import LogConfig, WLKNSLogger
from circuit_logging.otel import OpenTelemetryHandler
from opentelemetry.sdk._logs import LoggerProvider

provider = LoggerProvider()
handler = OpenTelemetryHandler(provider, config=cfg)
log.app.addHandler(handler)

Installation

# Von PyPI (empfohlen)
python3 -m pip install circuit-logging

# Mit OpenTelemetry-Unterstützung
python3 -m pip install "circuit-logging[otel]"

# Editable install (für Entwicklung)
python3 -m pip install -e ".[dev]"

Entwicklung

# Tests
python3 -m pytest tests/

# Lint
ruff check src/ tests/

# Format
ruff format src/ tests/

Architektur

src/circuit_logging/
├── __init__.py   → LogConfig, WLKNSLogger, AuditFileHandler, DailySalt, check_integrity
├── config.py     → LogConfig (service_name, version, environment)
├── logger.py     → WLKNSLogger mit 4 Welten
├── formatter.py  → JSONFormatter (redact + JSON output)
├── privacy.py    → redact() — rekursive Key-Filterung
├── integrity.py  → AuditFileHandler — verkettete SHA-256-Hashes
├── anonymize.py  → DailySalt + anonymize_ip() — GDPR-konforme IPs
├── rotation.py   → RotatingJSONHandler — tägliche Rotation für app/analytics
├── verify.py     → check_integrity() — programmatische Kettenprüfung
└── otel.py       → OpenTelemetryHandler — OTLP-Export (optional)

scripts/
└── verify_audit.py → CLI für Integritätsprüfung

Lizenz

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

circuit_logging-0.2.0.tar.gz (15.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

circuit_logging-0.2.0-py3-none-any.whl (13.5 kB view details)

Uploaded Python 3

File details

Details for the file circuit_logging-0.2.0.tar.gz.

File metadata

  • Download URL: circuit_logging-0.2.0.tar.gz
  • Upload date:
  • Size: 15.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for circuit_logging-0.2.0.tar.gz
Algorithm Hash digest
SHA256 4e2c180d3eeaea13180790b11a6abfc0d10717a26f21ecc6e956167277735d35
MD5 f066983da4c2d1b829298b80017f40b6
BLAKE2b-256 a5ce610014818296c6ca800baa1e6210b7aa487d5db18b39756396eb0674435e

See more details on using hashes here.

File details

Details for the file circuit_logging-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for circuit_logging-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4e8bc6fc749a1fe9fa1f4cb8d47397d8fe89ca1153fe207d76f0f50dcf83ba82
MD5 d2c550070ef2de3d635ffc3959a072d4
BLAKE2b-256 e975773b17020ad5b99037eeb6af2589d727d73d3e18240a921fbff94ec872dd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page