Build a structured logging standard: contexts, sampling, retention, and PII handling.
- User
Build a structured logging standard: contexts, sampling, retention, and PII handling.
- Assistant
Okay, the user is asking for a structured logging standard covering contexts, sampling, retention, and PII handling. This is a detailed technical request, so I need to provide a comprehensive yet actionable framework.
First, I should break down each component clearly. Contexts mean attaching metadata to logs—I'll define what fields are mandatory and optional. Sampling needs strategies to avoid data overload while preserving critical information, so I'll outline both static and dynamic approaches. Retention policies should balance compliance with storage costs, so I'll suggest tiered storage with automated deletion. PII handling is the most sensitive part—I need strict rules for masking, encryption, and access control.
I should structure this as a formal standard document with sections for each requirement, plus implementation examples and tooling recommendations. The user likely wants something they can directly adopt, so I'll include concrete field definitions, sample configs, and a checklist.
Since they mentioned "structured" logging, I'll emphasize JSON format and schema validation. For PII, I'll differentiate between data at rest and in transit. The retention part should reference common compliance timelines (GDPR, HIPAA). I'll avoid fluff—just clear rules with rationale.
Finally, I'll add a maturity model because teams may be at different adoption stages. The user might be a DevOps lead or security officer needing both immediate steps and long-term goals. I'll keep it neutral but practical, avoiding vendor lock-in while mentioning popular tools (Loki, Splunk) as examples.
Structured Logging Standard v1.0
1. Purpose & Principles
Standardize log data generation, handling, and lifecycle management to:
- Enable reliable observability, debugging, and audit trails
- Ensure regulatory compliance (GDPR, HIPAA, PCI-DSS, etc.)
- Minimize performance overhead and storage costs
- Protect sensitive information (PII/PHI/SPI)
Core Principles:
- Structured Only: All logs MUST be in machine-parseable formats (JSON, protobuf, etc.). Plain text logs are forbidden for new systems.
- Context-Rich: Every log entry must contain sufficient context for reconstruction.
- Least Privilege: Logs contain only necessary data; PII is masked/removed by default.
- Tamper-Evident: Log integrity is verifiable where required (e.g., cryptographic hashing).
2. Standard Log Schema (JSON Example)
All logs MUST conform to this base schema. Additional fields are allowed per domain.
{ "timestamp": "2024-01-15T10:23:45.123Z", // ISO 8601 UTC "level": "INFO", // DEBUG, INFO, WARN, ERROR, FATAL "trace_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", // UUID v4 "span_id": "a1b2c3d4", // 8-char hex for distributed tracing "service": "order-service", "hostname": "prod-order-07", "environment": "production", "version": "1.4.2", "component": "payment-processor", "message": "Payment processed successfully", "event": "payment.completed", // Canonical event name "http": { "method": "POST", "path": "/api/v1/payments", "status_code": 200, "request_id": "req-abc123" }, "user": { "id": "user_789", // NEVER log raw PII here "type": "authenticated" }, "error": { "code": "INVALID_CARD", "message": "Card expired" }, "custom": { "order_id": "ord_12345", "amount": 99.99, "currency": "USD" } }Mandatory Fields
Field Description timestampUTC with millisecond precision levelStandardized severity trace_idCorrelates distributed transactions span_idIdentifies operation within trace serviceService/application name environmentprod/staging/dev eventCanonical event identifier (snake_case) messageHuman-readable summary
3. Context Propagation Rules
3.1 Trace Context
- All inbound requests MUST extract
trace_id/span_idfrom headers:X-Trace-ID/X-Span-ID(custom) or W3C Trace Context (traceparent,tracestate)
- New root spans generate new
trace_id; child spans inherittrace_id, generate newspan_id. - No cross-environment leakage:
trace_idformat may vary by environment but must not expose internal details.
3.2 Business Context
Logs MUST include at least one business entity identifier (order_id, user_id, session_id, transaction_id). Never log:
- Raw email addresses, phone numbers, SSNs, full credit card numbers
- Passwords, API keys, JWTs (even if hashed)
- Unencrypted PII fields
3.3 System Context
Always include:
hostname,service,version,component. Optional but encouraged:region,availability_zone,deployment_id.
4. Sampling Strategy
4.1 Why Sample
- Control volume (especially for high-throughput services)
- Reduce storage/processing costs
- Prioritize error/performance logs
4.2 Sampling Rules
Log Level Default Rate Conditions DEBUG0.1% (or 0) Only if actively debugging INFO10% Random, consistent per trace_idWARN100% All warnings ERROR100% All errors FATAL100% All fatal errors 4.3 Dynamic Sampling (Adaptive)
Implement if volume exceeds thresholds:
- Rate limiting: Max N logs/sec per service
- Priority sampling: Increase rate for:
- Failed transactions
- Slow operations (>99th percentile)
- New/unseen error codes
- Consistent hashing: Sample deterministically by
trace_idto preserve transaction coherence.
5. PII & Sensitive Data Handling
5.1 Classification
Define data types per jurisdiction:
- PII: Name, email, phone, address, SSN, DOB, IP address (EU considers IP as PII)
- PHI: Health information (HIPAA)
- SPI: Sensitive personal info (special categories under GDPR)
- Secrets: API keys, passwords, tokens, private keys
5.2 Redaction Pipeline
Logs MUST pass through redaction before leaving the application boundary.
Redaction Rules:
- Field-level removal: Completely exclude sensitive fields (e.g.,
credit_card_numbernever logged). - Tokenization: Replace with non-reversible tokens where needed for correlation:
email→masked_email_abc123@example.comphone→+1-**-***-7890
- Hash for correlation: Use salted SHA-256 for internal linking (store salt separately, not in logs).
user_id_hash = SHA256(salt + user_id)
- Partial masking: Keep last 4 digits of cards/SSNs only.
5.3 PII Field Registry
Maintain a central registry (in code/config) of all PII fields and their redaction method. Example:
pii_fields: - path: $.user.email action: mask pattern: "(.{3}).*(@.*)" # → "$1$2" - path: $.payment.card_number action: remove - path: $.request.ip action: hash # if needed for geo-analysis
6. Retention & Storage
6.1 Tiered Retention Policy
Tier Duration Storage Use Case Hot 7-30 days SSD/Elasticsearch Active debugging Warm 90 days Object storage (S3) Incident investigation Cold 1-7 years Archival storage (Glacier) Compliance/audit Deleted > retention period Securely erased N/A Retention by Log Level:
ERROR/FATAL: 2 years minimum (compliance)WARN: 1 yearINFO: 30 daysDEBUG: 7 days (or 0 in prod)
6.2 Compliance Exceptions
Extend retention for:
- Financial audits (PCI-DSS: 1 year)
- Healthcare (HIPAA: 6 years)
- GDPR “right to audit” requests
6.3 Automated Lifecycle
- Use bucket lifecycle policies (S3, GCS) or ILM (Elasticsearch).
- Never manually delete logs. Automated only.
- Log deletion must be auditable (who/when/why).
7. Security & Access
7.1 Encryption
- In transit: TLS 1.2+ everywhere
- At rest: Platform-managed keys (KMS, Cloud HSM) for logs >30 days
- Client-side encryption for highly regulated data (optional)
7.2 Access Control
- RBAC: Log access via roles (developer, operator, auditor).
- Least privilege: Developers see only their service’s logs by default.
- PII-scoped access: Extra approval required to view unmasked PII.
- Audit all access: Log every log-query (who, what, when).
8. Implementation Checklist
Mandatory
- All services emit JSON logs to stdout/stderr
-
trace_id/span_idpropagated across service boundaries - PII redaction library integrated in logging pipeline
- Sampling configured based on section 4
- Log storage encrypted at rest
- Retention policies automated
- Central log aggregation (Loki, ELK, Splunk, Datadog) with access controls
Recommended
- Structured logging library (e.g., Serilog, Winston, Zap) with schema enforcement
- Log-based metrics/alerts on error rates, latency
- Periodic audit of PII in logs (automated scanning)
- Chaos testing: verify logs persist during failures
- Cost monitoring alerts (log volume spikes)
9. Validation & Compliance
9.1 Schema Validation
Log ingestion pipeline MUST reject non-conforming logs. Use JSON Schema:
{ "$schema": "http://json-schema.org/draft-07/schema#", "required": ["timestamp", "level", "trace_id", "service", "event"], "properties": { "timestamp": { "type": "string", "format": "date-time" }, "level": { "enum": ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"] } } }9.2 PII Scanning
Weekly scan of log storage for:
- Credit card patterns (Luhn check)
- Email/phone regexes
- Known PII field names (“ssn”, “dob”) Alert on violations.
9.3 Audit Reports
Generate quarterly:
- Log volume by service/level
- PII redaction coverage
- Access logs (who queried what)
- Retention compliance status
10. Tooling Recommendations
- Logging Libraries: Zap (Go), Serilog (.NET), Winston (Node.js), Logback (Java)
- Aggregation: Grafana Loki (cost-effective), Elasticsearch, Splunk, Datadog
- Redaction: Custom middleware, OpenRewrite rules, or commercial DLP solutions
- Sampling: Implement in logging lib or sidecar (e.g., OpenTelemetry Collector)
- Schema Validation: JSON Schema validators, Confluent Schema Registry (for Kafka)
11. Exceptions & Emergencies
- Emergency Debugging: Can temporarily disable sampling/redaction for <24h with post-mortem justification.
- Legacy Systems: Phase in compliance. Document gaps and mitigation (network segmentation, access controls).
- Legal Hold: Override deletion upon legal request; document in chain-of-custody log.
Approval: This standard requires sign-off from Security, Compliance, SRE, and Engineering Leadership.
Review Cycle: Annually or after major regulatory changes.Last updated: 2024-01-15
Owner: Observability Team
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.