The user wants a "structured logging contract catalog."
This implies a system design or engineering artifact that defines how logging should be done within a software system.
It needs to cover three specific areas:
- Fields: The schema of the logs (what data goes in, what are the standard keys).
- Redaction Policy: How sensitive data is handled (masking, hashing, or blocking).
- Validation Tests: How to ensure the logs adhere to the contract (unit tests, integration tests, schema validation).
Target Audience: Software engineers, DevOps/SREs, security teams.
Format: A comprehensive document or a set of configuration files (e.g., YAML/JSON) plus testing code snippets.
Step 1: Define the Philosophy/Context.
Structured logging usually means JSON. It needs to be machine-readable.
I should structure the response as a formal specification that a team could actually adopt.
Step 2: Section 1 - Field Catalog (The Schema).
I need to categorize fields.
- Standard/Context:
timestamp, level, service_name, trace_id.
- Request/Response:
method, path, status_code, latency_ms.
- User/Actor:
user_id, tenant_id.
- Custom/Business:
order_id, payment_amount.
Self-Correction during thought process: I should specify data types and whether a field is mandatory.
Step 3: Section 2 - Redaction Policy (Security).
This is crucial for compliance (GDPR, HIPAA).
- Blocklist: Passwords, credit cards, API keys.
- Patterns: Regex matching (e.g., email, SSN).
- Mechanism: How to mask (e.g.,
***** or hashing).
Step 4: Section 3 - Validation Tests (Quality Assurance).
How do we enforce this?
- Schema Validation: Using tools like JSON Schema.
- Unit Tests: Testing the logger wrapper itself (mocking the output).
- Integration Tests: Checking actual logs in a staging environment (e.g., parsing the output stream).
- Compliance Checks: Asserting no PII exists in sample logs.
Step 5: Formatting the Output.
I will use a mix of Markdown tables, JSON/YAML examples, and pseudo-code/Python snippets to make it concrete and actionable.
Drafting the Structure:
- Introduction: Purpose of the catalog.
- Part 1: The Field Schema (The "What"):
- Base fields.
- HTTP context.
- Error details.
- Part 2: Redaction & Sanitization (The "How Safe"):
- Strict rules.
- Implementation pattern.
- Part 3: Validation Strategy (The "Proof"):
- Unit test examples.
- Schema validation (JSON Schema).
- Part 4: Implementation Example (Python/Pythonic).
Let's refine the content.
Fields:
timestamp: ISO8601 UTC.
level: standard RFC 5424 (debug, info, error...).
message: human-readable.
trace_id: distributed tracing.
stack_trace: only on errors.
Redaction:
- Need a clear list of keywords (password, secret, token).
- Need regex patterns for PII (email, phone).
Validation:
- Test that sensitive keys are redacted.
- Test that types are correct (int vs string).
- Test that trace IDs are present.
Let's build the response.
This Structured Logging Contract Catalog defines the schema, security policies, and validation requirements for generating logs across services. This ensures logs are machine-readable, searchable, and compliant with privacy standards.
1. Field Schema Catalog
All logs must be emitted as JSON objects. The schema is divided into Mandatory (must exist) and Contextual (optional but standardized) fields.
1.1 Mandatory Core Fields
These fields must be present in every single log entry.
| Field Name | Type | Description | Example |
|---|
timestamp | String | ISO 8601 UTC timestamp with milliseconds. | 2023-10-27T14:30:00.123Z |
level | String | Severity level (RFC 5424). Enum: DEBUG, INFO, WARN, ERROR, CRITICAL. | INFO |
message | String | Human-readable summary of the event. | User successfully logged in |
service_name | String | Canonical name of the emitting service. | payment-gateway |
trace_id | String | Distributed tracing ID (W3C Trace Context or Jaeger). | 4bf92f3577b34da6 |
span_id | String | Specific request span ID. | 00f067aa0ba902b7 |
1.2 Contextual & Event Fields
These fields should be included when relevant to the event context.
| Field Name | Type | Description | Example |
|---|
user_id | String | ID of the authenticated user acting. | usr_834 |
tenant_id | String | ID for multi-tenant isolation. | acme-corp |
http_method | String | HTTP method (if applicable). | POST |
http_path | String | Request path (sanitized). | /api/v1/users/{id} |
status_code | Integer | HTTP response status code. | 201 |
latency_ms | Integer | Request duration in milliseconds. | 42 |
error_code | String | Internal application error code. | E_DB_CONN_FAIL |
stack_trace | String | Exception stack trace (only on ERROR level). | File "app.py", line 42... |
2. Redaction Policy (Security & Compliance)
To prevent leaking Personally Identifiable Information (PII) and credentials, the logging library must apply redaction rules before serialization.
2.1 Redaction Rules Table
| Category | Policy | Matching Pattern (Regex/Key) | Output Value |
|---|
| Passwords | REDACT | Keys: password, passwd, pwd, secret | ***** |
| Auth Tokens | MASK | Keys: authorization, api_key, access_token | Bearer ****...**** (First 4/Last 4) |
| Credit Cards | MASK | Regex: \b\d{13,16}\b | ****-****-****-1234 |
| Emails | HASH | Regex: ^[^@]+@[^@]+\.[^@]+$ | a1b2c3d4@example.com |
| SSN | BLOCK | Regex: ^\d{3}-\d{2}-\d{4}$ | [REDACTED_PII] |
2.2 Implementation Logic
- Key Matching: If a JSON key matches a blocklist string (case-insensitive), the value is replaced.
- Value Pattern Scanning: (Optional) Scan string values for high-risk formats (like CC numbers) and mask them.
- Depth Limit: If a nested object exceeds 5 levels, replace the value with
[MAX_DEPTH_EXCEEDED] to prevent circular reference memory leaks.
3. Validation Tests (Contract Tests)
Every service using this logging library must pass the following "Contract Tests" to ensure compliance. These should be implemented as unit tests within the service's codebase.
Test 1: Schema Compliance
Objective: Ensure all mandatory fields exist and have correct types.
def test_log_schema_compliance():
log_output = capture_log(my_service_function)
# 1. Check mandatory keys
mandatory_keys = ["timestamp", "level", "message", "service_name", "trace_id"]
for key in mandatory_keys:
assert key in log_output, f"Missing mandatory key: {key}"
# 2. Check timestamp format
try:
datetime.strptime(log_output['timestamp'], "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
assert False, "Timestamp not in ISO 8601 UTC format"
# 3. Check level validity
assert log_output['level'] in ["DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"]
Test 2: Redaction Verification
Objective: Ensure sensitive data never appears in logs.
def test_pii_redaction():
# Simulate input with sensitive data
sensitive_data = {
"username": "jdoe",
"password": "super_secret_123",
"email": "jdoe@example.com"
}
# Call the logger
logger.info("User login attempt", extra=sensitive_data)
log_output = get_last_log()
# Assertions
assert log_output['password'] == "*****", "Password was not redacted"
assert "super_secret_123" not in str(log_output), "Raw password found in log stream"
assert log_output['email'] != "jdoe@example.com", "Email was not hashed/masked"
Test 3: Error Handling Structure
Objective: Ensure errors contain stack traces and error codes.
def test_error_structure():
try:
raise DatabaseConnectionError("Timeout")
except Exception:
logger.exception("DB failure")
log_output = get_last_log()
assert log_output['level'] == "ERROR"
assert 'stack_trace' in log_output
assert "Traceback" in log_output['stack_trace']
assert log_output['error_code'] is not None
Test 4: Trace Context Propagation
Objective: Ensure logs include Trace IDs when context is active.
def test_trace_injection():
trace_id = start_trace_scope("test-trace-123")
logger.info("Processing item")
log_output = get_last_log()
assert log_output['trace_id'] == "test-trace-123"
assert log_output['span_id'] is not None