We are going to create a structured logging contract catalog. The catalog should include:
Fields: A list of standard fields and their descriptions, data types, and possible values (if applicable).
Redaction policy: Rules for which fields should be redacted (masked) and how (e.g., replace with asterisks, hash, etc.).
Validation tests: A set of tests to validate that logs conform to the contract, including required fields, data types, and redaction.
Let's assume we are building a generic logging system for an application. We'll define a set of common fields and then extend with custom fields.
We'll define the following standard fields (based on common practices and the Elastic Common Schema (ECS) as a reference, but simplified for this example):
Standard Fields:
timestamp: The time when the log event occurred (ISO 8601 format).
log.level: The severity level of the log (e.g., "DEBUG", "INFO", "WARN", "ERROR", "FATAL").
message: The log message (string).
service.name: The name of the service generating the log.
service.version: The version of the service.
environment: The environment (e.g., "production", "staging", "development").
trace.id: A unique identifier for the trace (if applicable, for distributed tracing).
span.id: A unique identifier for the span (if applicable, within a trace).
user.id: The identifier of the user associated with the log (if applicable). This is sensitive and may need redaction.
Custom Fields:
We allow additional fields, but they must follow the same rules (e.g., no sensitive data without redaction, proper types).
Redaction Policy:
We define a list of field names (or patterns) that are considered sensitive and must be redacted before logging.
Examples of sensitive fields: user.id, user.email, user.ssn, credit_card_number, etc.
Redaction method: For string fields, replace with a fixed string (like "REDACTED") or a fixed number of asterisks (e.g., "****").
For non-string fields, we might convert to string and then redact, or use a placeholder appropriate for the type.
Validation Tests:
We need to validate that every log entry:
a) Has the required fields (timestamp, log.level, message, service.name, environment).
b) The data types of each field are correct.
c) Any sensitive field (as per redaction policy) is redacted (i.e., does not contain the original value).
d) The log.level is one of the allowed values.
e) The timestamp is a valid ISO 8601 string and in the correct timezone (if required, we might allow any but usually UTC).
We might also validate that there are no extra fields that are not allowed? (Usually we allow extra fields, but we might want to check that they are not sensitive and unredacted.)
However, note that in structured logging, we often allow arbitrary fields. So we might not forbid extra fields, but we must check that if they match a sensitive pattern, they are redacted.
Let's define:
Required Fields:
timestamp (string, ISO8601)
log.level (string, one of: DEBUG, INFO, WARN, ERROR, FATAL)
message (string)
service.name (string)
environment (string)
Optional Fields (standard):
service.version (string)
trace.id (string)
span.id (string)
user.id (string)
Redaction Policy:
We define a list of field names that are sensitive and must be redacted. For this example, let's say:
sensitive_fields = ["user.id", "user.email", "user.ssn", "credit_card_number", "password"]
But note: we might also have fields that are not in this list but contain sensitive data? We cannot know all. So we rely on the developer to mark fields as sensitive by naming convention? Or we can have a configuration that maps field names to redaction.
However, in practice, we might have a config that specifies:
- Which fields are sensitive (by exact name or by regex pattern).
- How to redact (by field name or by type?).
For simplicity, let's assume we have a set of field names (exact match) that are sensitive and must be redacted by replacing the entire value with "REDACTED".
But note: sometimes we might want to partially redact (like credit card: only show last 4 digits). So we might have different redaction strategies per field.
Let's define a redaction policy as a list of rules:
code
{
"field": "user.id",
"strategy": "replace", // replace entire value with a fixed string
"replacement": "REDACTED"
},
{
"field": "credit_card_number",
"strategy": "mask", // mask all but last 4
"mask_char": "*",
"visible_digits": 4
}
However, for simplicity in validation, we might just check that the sensitive fields are not equal to the original (if we know the original) or that they are in a redacted format? But we don't have the original.
Alternatively, we can have the logging library responsible for redaction, and then the validation just checks that if a field is in the sensitive list, then its value must be in a redacted form (e.g., for user.id, it must be exactly "REDACTED", for credit card it must be a string of asterisks with 4 digits at the end?).
This is complex. Let's simplify for the contract:
We will say: any field that is in the sensitive_fields list must be redacted by replacing the entire value with the string "REDACTED". So we don't do partial masking.
Then the validation test for redaction is: if a field name is in sensitive_fields, then its value must be exactly "REDACTED".
But wait, what if the field is not present? That's okay, because it's optional. But if it is present, it must be redacted.
However, note: we might have a field that is not in the sensitive list but contains sensitive data? We cannot catch that by field name. So we rely on the developer to not log sensitive data in non-sensitive fields, or to use a different mechanism (like not logging at all). The redaction policy is by field name.
So:
Redaction Policy:
- For each field in the predefined sensitive_fields list, if the field appears in the log, its value must be exactly the string "REDACTED".
But what about non-string fields? We are going to require that the sensitive fields are strings? Or we can convert to string and then redact? Let's say: the sensitive fields must be of type string and then redacted to "REDACTED". So if we see a non-string in a sensitive field, that's a validation error.
Alternatively, we can have a rule that says: if a field is in the sensitive list, then regardless of type, we expect it to be redacted. But how do we redact a number? We might convert to string and then redact? So we can say: the value after redaction must be a string and equal to "REDACTED". So the logging library must convert any sensitive field to string and then set to "REDACTED".
So in the log, we expect the sensitive field to be a string with value "REDACTED".
Validation Tests:
We will write a set of tests that take a log entry (as a dictionary/JSON) and check:
Required fields are present.
The data types of each field are as expected.
timestamp: string (and we can try to parse as ISO8601? but for validation we might just check string and format with regex? or use a library)
log.level: string and in allowed list.
message: string.
service.name: string.
environment: string.
For any field that is in the sensitive_fields list (and is present in the log), the value must be the string "REDACTED".
For standard optional fields, if present, they must be of the correct type (string for service.version, trace.id, span.id, user.id).
We might also want to check that there are no fields that are not allowed? But we are allowing custom fields. So we don't restrict extra fields, except that if they are in the sensitive list, they must be redacted.
However, note: the sensitive_fields list might include fields that are not standard. For example, we might have "user.email" as sensitive. So we must check any field that is in that list, even if it's custom.
So we have two sets of fields:
- standard fields (required and optional) with expected types.
- sensitive fields (by name) that must be redacted if present.
We can have a third set: fields that are allowed but not required? We don't have a fixed set of custom fields, so we don't validate their types unless they are in the sensitive list (then we check they are redacted) or if they are standard.
So:
For each field in the log entry:
code
If the field is in the standard fields (required or optional), check type.
If the field is in the sensitive_fields list, check that the value is exactly "REDACTED" (and that it is a string?).
But note: a field can be both standard and sensitive (like user.id). So we must check both: it is present (if required) and if present, it must be redacted? Actually, if it's required and sensitive, then we require it to be present and redacted? That doesn't make sense because if it's required, we must have it, but then it's redacted so we don't have the real value.
Let's clarify:
Required fields are fields that must be present in every log. But if a required field is also sensitive, then we must have it, but it must be redacted? That would mean we are logging a redacted user.id for every user? That might not be the case. We might not have a user.id for anonymous users.
So perhaps we should separate:
Required fields: must be present and non-redacted (because they are necessary for the log context).
Sensitive fields: if present, must be redacted.
But then a field can be both required and sensitive? That would be a contradiction. So we should not have a field that is both required and sensitive. Because if it's required, we need the real value for the log to be useful, but if it's sensitive, we don't want to log the real value.
Therefore, we should design the standard fields such that none of the required fields are sensitive. So:
Optional standard fields (some might be sensitive?):
service.version (non-sensitive), trace.id (non-sensitive? but could be used to link to user, so maybe not sensitive), span.id (non-sensitive), user.id (sensitive).
But then we have a separate list of sensitive fields? We can mark in the standard_fields which are sensitive.
Alternatively, we can have:
code
sensitive_fields = ["user.id", "user.email", ...]
And then the standard_fields definition doesn't include sensitivity. But then we have to check two things for a field that is in both: it must be of the correct type (from standard_fields) and if present and in sensitive_fields, it must be redacted.
However, for user.id, we want it to be a string (from standard_fields) and if present, it must be redacted (from sensitive_fields). But note: if it's required? We said it's optional. So if it's present, it must be redacted.
But what if we want to log the user.id for non-sensitive operations? Then we might not want to redact it. So maybe we should not mark user.id as sensitive by default? It depends on the privacy policy.
Let's assume that in our organization, user.id is considered sensitive and must be redacted in logs. So we mark it as sensitive.
Then, if we have a log entry with user.id, it must be redacted. But what if we need to log the user.id for debugging? Then we might have a separate way (like only in debug mode and then we have a different redaction policy?).
For simplicity, we'll stick to: if a field is in the sensitive list, it must be redacted whenever it appears.
And then we also allow custom fields. For custom fields, if they are in the sensitive_fields list (by exact name) then they must be redacted. But we don't have a type for custom fields? We can skip type check for custom fields? Or we can say: custom fields can be any type, but if they are sensitive (by name) then they must be a string and equal to "REDACTED".
But wait, what if a custom field is sensitive but we want to log it in a redacted form that is not just "REDACTED"? Then we need a more flexible redaction policy.
Given the complexity, let's stick to:
We have a list of field names that are considered sensitive. For any field in this list, if it appears in the log, its value must be exactly the string "REDACTED".
We have a set of standard fields (with their types and required flag). For standard fields, we check the type and required condition.
For custom fields (not in standard_fields), we don't check type, but if the field name is in the sensitive list, then we check that the value is "REDACTED".
If key in standard_fields:
Check that the value is of the type specified (if the value is None, that might be allowed? We'll say: if required, must be non-null? and if optional, can be null? Let's say: for required, must be present and non-null; for optional, if present, must be of the correct type and non-null? But sometimes we might want to allow null for optional? We'll say: for optional, if present, must be of correct type and non-null. If not present, that's okay.
If key in sensitive_fields (and key is present in the log):
Check that the value is exactly the string "REDACTED".
But note: what if a field is in both? For example, user.id is in standard_fields and sensitive_fields. Then we check both: it must be a string (from standard_fields) and if present, it must be "REDACTED" (from sensitive_fields). But note: the standard_fields says it's optional, so it might not be present. If present, it must be a string and "REDACTED".
However, if we have a custom field that is in the sensitive list, we don't have a type in standard_fields, so we only check that if present, it is "REDACTED".
But wait, what if a sensitive field is not in standard_fields? Then we don't check its type? We only check that if present, it is "REDACTED". But then we are not checking that it is a string? We are checking that the value is exactly "REDACTED", which is a string. So that implies it must be a string.
So for sensitive fields (whether standard or custom), if present, they must be the string "REDACTED".
But then for standard fields that are not sensitive, we check the type.
So:
Steps for validation of a log entry (dict):
Check required standard fields are present and non-null.
For every key in the log:
a. If the key is in standard_fields, check the type (and allowed_values for log.level).
b. If the key is in sensitive_fields, check that the value is exactly "REDACTED".
But note: what if a field is in sensitive_fields but not in standard_fields? Then we only do step 2b.
What if a field is in standard_fields but not in sensitive_fields? Then we only do step 2a.
What if a field is in both? Then we do both.
However, note: for a field that is in both, step 2a requires it to be a string (from standard_fields) and step 2b requires it to be "REDACTED". So that's consistent.
But what about the allowed_values for log.level? We check that in step 2a.
Now, what about the timestamp format? We said it's a string and ISO8601. We might want to validate the format. We can do:
code
For timestamp: try to parse with datetime.fromisoformat (if using Python) or use a regex. But for the contract, we can say it must be a string and match the ISO8601 format.
We can have a more detailed type check for timestamp: string that matches a regex for ISO8601.
However, for simplicity, we can just check it's a string and then try to parse it in the test? But the contract is about the structure, so we can say:
code
timestamp: string, must be in ISO8601 format (e.g., "2024-01-01T12:00:00Z").
We can write a regex for ISO8601, but note that there are many variations. We might use a library to parse and if it parses without error, it's valid.
For the purpose of this catalog, we'll define:
code
Fields:
Field Name | Type | Required | Allowed Values | Sensitive | Description
------------------|--------|----------|----------------------|-----------|------------
timestamp | string | Yes | ISO8601 datetime | No | Event time in ISO8601 format.
log.level | string | Yes | DEBUG, INFO, WARN, ERROR, FATAL | No | Log level.
message | string | Yes | any | No | Log message.
service.name | string | Yes | any | No | Name of the service.
environment | string | Yes | e.g., production, staging, development | No | Environment.
service.version | string | No | any | No | Version of the service.
trace.id | string | No | any | No | Trace ID for distributed tracing.
span.id | string | No | any | No | Span ID within a trace.
user.id | string | No | any | Yes | User identifier. Must be redacted if present.
Custom fields: any additional fields. If the field name is in the sensitive list, then if present, the value must be exactly "REDACTED".
Sensitive fields list: ["user.id", "user.email", "user.ssn", "credit_card_number", "password"]
Now, the validation tests:
We can write a function that takes a log entry (dict) and returns a list of errors.
Steps:
errors = []
Step 1: Check required fields.
for field in required_fields (which are the standard_fields with required=True):
if field not in log or log[field] is None:
errors.append(f"Missing required field: {field}")
Step 2: For each key in the log:
a. If key in standard_fields:
- Check type:
if standard_fields[key]["type"] == "string":
if not isinstance(log[key], str):
errors.append(f"Field {key} must be a string.")
# We only have string types in our example, but could extend.
- If key == "log.level":
if log[key] not in standard_fields[key]["allowed_values"]:
errors.append(f"Field log.level must be one of {standard_fields[key]['allowed_values']}")
- For timestamp, we can additionally check the format? We can do that in a separate step or here.
code
b. If key in sensitive_fields:
if log[key] != "REDACTED":
errors.append(f"Sensitive field {key} must be redacted to 'REDACTED'")
Step 3: Additional checks for specific fields:
code
For timestamp: if present, check it's a valid ISO8601 string. We can write a function to check.
However, note: what if a field is in standard_fields and also in sensitive_fields? We do both a and b.
But what about the type check for sensitive fields? In step a, we check the type (string) and in step b we check the value. So that's okay.
But note: for a sensitive field that is not in standard_fields (custom sensitive field), we only do step b. We don't check the type? But step b requires the value to be the string "REDACTED", so that implies it's a string. So that's okay.
However, what if the custom sensitive field is not a string? Then step b will fail because we compare to a string. So we must ensure that the value is a string and equal to "REDACTED". But what if it's a number? Then the comparison will be false, and we report an error. So that's okay.
But what if the custom sensitive field is a string but not "REDACTED"? Then we report an error.
So the validation is:
code
For every field in the log:
If it's in standard_fields, check type and allowed values (if applicable).
If it's in sensitive_fields, check value is "REDACTED".
However, note: the sensitive_fields list might include fields that are not standard. We are okay with that.
But what if a standard field is not in the sensitive list, but we want to consider it sensitive? Then we must add it to the sensitive list. So the sensitive list is independent.
Let's adjust: the sensitive_fields list is a list of field names (exact match) that are considered sensitive. We can have:
code
sensitive_fields = ["user.id", "user.email", ...]
And then in the standard_fields, we don't mark which are sensitive. We just have a separate list.
But then how do we know that user.id is both standard and sensitive? We don't need to know in the standard_fields definition. We just have:
code
standard_fields: defines the expected type and required for known fields.
sensitive_fields: defines which fields must be redacted if present.
So the validation function:
code
def validate_log(log_entry):
errors = []
# Check required standard fields
for field, meta in standard_fields.items():
if meta["required"]:
if field not in log_entry or log_entry[field] is None:
errors.append(f"Missing required field: {field}")
# Check each key in the log_entry
for key, value in log_entry.items():
# Check if it's a standard field
if key in standard_fields:
meta = standard_fields[key]
# Check type
if meta["type"] == "string" and not isinstance(value, str):
errors.append(f"Field {key} must be a string.")
# Check allowed values for log.level
if key == "log.level" and "allowed_values" in meta:
if value not in meta["allowed_values"]:
errors.append(f"Field {key} must be one of {meta['allowed_values']}")
# Check timestamp format? We can do that separately for the timestamp field.
if key == "timestamp":
if not is_valid_iso8601(value):
errors.append(f"Field {key} must be a valid ISO8601 string.")
# Check if it's a sensitive field
if key in sensitive_fields:
if value != "REDACTED":
errors.append(f"Sensitive field {key} must be exactly 'REDACTED'")
return errors
But note: what if a field is in sensitive_fields and also in standard_fields? Then we do both checks. That's okay.
However, what if a field is in sensitive_fields but not in standard_fields? Then we skip the type check (from standard_fields) and only do the redaction check.
But what about the type of the sensitive field? We are only checking that it's equal to "REDACTED", which is a string. So if it's not a string, the comparison will be false and we get an error. But the error message will be about redaction, not type. That might be confusing.
We could adjust: if a field is in sensitive_fields, we check that it is a string and equal to "REDACTED". But then we are doing a type check for sensitive fields that are not standard.
Alternatively, we can say: for any field in sensitive_fields, if present, it must be a string and equal to "REDACTED". So we can change the sensitive check to:
code
if key in sensitive_fields:
if not isinstance(value, str) or value != "REDACTED":
errors.append(f"Sensitive field {key} must be a string and exactly 'REDACTED'")
But then if the field is also in standard_fields and we already checked the type (string) then we are checking twice? That's okay.
However, what if the standard_fields says the type is something else? Then we have a conflict. But if a field is in both, then the standard_fields type must be string because we require it to be "REDACTED". So we should enforce that in the standard_fields definition? Or we can let the validation catch it: if the standard_fields says it's an integer, but we require it to be a string and "REDACTED", then that's a conflict in the contract.
So we must ensure that the standard_fields definition for a sensitive field has type string.
In our example, user.id is a string in standard_fields and also sensitive. That's consistent.
So let's adjust the validation:
code
for key, value in log_entry.items():
# Check standard field type and allowed values
if key in standard_fields:
meta = standard_fields[key]
if meta["type"] == "string" and not isinstance(value, str):
errors.append(f"Field {key} must be a string.")
if key == "log.level" and value not in meta["allowed_values"]:
errors.append(f"Field {key} must be one of {meta['allowed_values']}")
if key == "timestamp" and not is_valid_iso8601(value):
errors.append(f"Field {key} must be a valid ISO8601 string.")
# Check sensitive field
if key in sensitive_fields:
if not isinstance(value, str) or value != "REDACTED":
errors.append(f"Sensitive field {key} must be a string and exactly 'REDACTED'")
But wait, what if a standard field is not sensitive and we have a type that is not string? We only check string types. We might have other types in the future? For now, we only have strings.
We can extend the standard_fields to have multiple types. But for simplicity, we'll keep all as string.
Now, what about the allowed values for log.level? We check that only if the key is "log.level". But what if we have other standard fields with allowed values? We can extend the meta to have an "allowed_values" key and then check:
code
if "allowed_values" in meta and value not in meta["allowed_values"]:
But then we are checking for every standard field? That's okay.
So:
code
if key in standard_fields:
meta = standard_fields[key]
# Check type
expected_type = meta["type"]
if expected_type == "string":
if not isinstance(value, str):
errors.append(f"Field {key} must be a string.")
# ... other types
if "allowed_values" in meta:
if value not in meta["allowed_values"]:
errors.append(f"Field {key} must be one of {meta['allowed_values']}")
But note: for log.level, we have allowed_values. We don't have for others.
Now, for timestamp, we have a special format check. We can do:
code
if key == "timestamp":
if not is_valid_iso8601(value):
errors.append(...)
Alternatively, we can have a "format" key in meta for string fields? But that's getting complex.
Given the above, let's write the catalog:
Structured Logging Contract Catalog
Fields:
Standard Fields (with metadata):
Field Type Required Allowed Values Sensitive Description
---------------|--------|------------|-----------------------------------|-----------|------------
timestamp string Yes ISO8601 datetime string No Event time in ISO8601 format.
log.level string Yes DEBUG, INFO, WARN, ERROR, FATAL No Log level.
message string Yes any No Log message.
service.name string Yes any No Name of the service.
environment string Yes e.g., production, staging, dev No Environment.
service.version string No any No Service version.
trace.id string No any No Trace ID for distributed tracing.
span.id string No any No Span ID within a trace.
user.id string No any Yes User identifier. Must be redacted if present.
Note: Additional custom fields are allowed. If a custom field name is in the sensitive_fields list, then it must be redacted (value exactly "REDACTED").
For any field (standard or custom) that is in the sensitive_fields list, if the field is present in the log entry, its value must be exactly the string "REDACTED".
Redaction must be applied by the logging library before the log is emitted.
Validation Tests:
We will validate each log entry against the following:
a. All required standard fields (timestamp, log.level, message, service.name, environment) must be present and non-null.
b. For every field in the log entry:
- If the field is a standard field, check the data type (currently only string) and allowed values (for log.level).
- Additionally, for the timestamp field, check that it is a valid ISO8601 string.
- If the field is in the sensitive_fields list, check that the value is exactly the string "REDACTED".
c. For standard fields that are not present and are optional, that's acceptable.
d. For custom fields (not in standard_fields), no type checking is performed except if they are in the sensitive_fields list (then they must be "REDACTED").
e. The log.level must be one of the allowed values.
Example validation function (in Python-like pseudocode):
Note: This is a basic example. In a real system, we might have more complex types (numbers, booleans, objects) and more complex redaction strategies.
Also, note that the sensitive_fields list might be provided as a configuration and can be extended.
We might also want to allow a field to be partially redacted? Then we would need a more complex policy that specifies how to redact each sensitive field.
But for the contract, we are keeping it simple: entire field replaced by "REDACTED".
Finally, we should also consider that the logging library must enforce redaction at the point of logging. The validation tests are for ensuring that the logs that are emitted conform to the contract. But the logging library should have built-in redaction so that the application code doesn't have to worry about it.
So the contract is for the output of the logging library.
We can also have a test that the logging library, when given a log entry with a sensitive field, will redact it. But that's an implementation test of the library, not the contract.
The contract is about the structure of the log events that are emitted.
This catalog defines the structure and the rules.
Let me know if you have any questions or need adjustments.
I'll create a comprehensive structured logging contract catalog with fields, redaction policies, and validation tests. This follows security best practices while maintaining operational utility.
Structured Logging Contract Catalog
1. Standard Field Definitions
A. Core Metadata Fields
Field
Type
Required
Description
Examples
timestamp
string (ISO 8601)
Yes
Event occurrence time with timezone
"2024-01-15T10:30:45.123Z"
log_level
enum
Yes
Severity level
"DEBUG", "INFO", "WARN", "ERROR", "FATAL"
service.name
string
Yes
Microservice/application name
"payment-service"
service.version
string
Yes
Semantic version
"1.2.3"
environment
enum
Yes
Deployment environment
"prod", "staging", "dev"
trace_id
string (UUID)
Conditional*
Distributed trace ID
"550e8400-e29b-41d4-a716-446655440000"
span_id
string (UUID)
Conditional*
Span ID within trace
"550e8400-e29b-41d4-a716-446655440001"
hostname
string
No
Host where event originated
"payment-prod-01"
*Required for distributed tracing contexts
B. Contextual Fields
Field
Type
Required
Description
Redaction
user.id
string
No
Internal user identifier
Always
user.session_id
string
No
Session identifier
Always
request.id
string
No
Request correlation ID
No
transaction_id
string
No
Business transaction ID
No
http.method
string
Conditional*
HTTP method
No
http.status_code
integer
Conditional*
HTTP response code
No
http.url
string
Conditional*
Full URL (without query params)
Partial
http.user_agent
string
Conditional*
Client user agent
Partial
event.action
string
Yes
What happened
No
event.category
string
Yes
Event classification
No
event.outcome
enum
Yes
Success/failure
"success", "failure"
*Required when logging HTTP events
C. Error/Exception Fields
Field
Type
Required
Description
error.type
string
Conditional*
Exception class name
error.message
string
Conditional*
Error message
error.stack_trace
string
Conditional*
Full stack trace
*Required when log_level is ERROR or FATAL
D. Custom/Extension Fields
Field
Type
Required
Description
Naming Convention
custom.*
any
No
Domain-specific data
custom.<domain>.<field>
metrics.*
number
No
Numeric measurements
metrics.<name>
Naming Rules for Custom Fields:
Prefix with custom. or metrics.
Use lowercase with underscores
Max 64 characters per field name
No reserved prefixes: log_, event_, error_, user_, http_
def test_required_fields_present():
"""All required fields must exist"""
required = ["timestamp", "log_level", "service.name",
"service.version", "environment", "event.action",
"event.category", "event.outcome"]
for log in sample_logs:
for field in required:
assert field in log, f"Missing required field: {field}"
def test_timestamp_format():
"""Timestamp must be valid ISO 8601"""
import re
iso8601_regex = r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$'
for log in sample_logs:
assert re.match(iso8601_regex, log["timestamp"])
def test_log_level_values():
"""log_level must be from allowed set"""
allowed = ["DEBUG", "INFO", "WARN", "ERROR", "FATAL"]
for log in sample_logs:
assert log["log_level"] in allowed
def test_service_name_format():
"""Service name must be lowercase alphanumeric with hyphens"""
import re
pattern = r'^[a-z0-9]+(?:-[a-z0-9]+)*$'
for log in sample_logs:
assert re.match(pattern, log["service.name"])
def test_event_fields():
"""Event fields must be non-empty strings"""
for log in sample_logs:
assert isinstance(log["event.action"], str) and log["event.action"]
assert isinstance(log["event.category"], str) and log["event.category"]
assert log["event.outcome"] in ["success", "failure"]
B. Redaction Validation Tests
python
def test_sensitive_fields_redacted():
"""All sensitive fields must be fully redacted"""
sensitive_patterns = [
r"user\..*",
r".*\.email",
r".*\.phone",
r".*\.ssn",
r".*\.password",
r".*\.token",
r".*\.secret",
r".*\.key"
]
for log in sample_logs:
for field in log:
if any(re.match(pattern, field) for pattern in sensitive_patterns):
assert log[field] == "REDACTED", \
f"Field {field} should be redacted but got: {log[field]}"
def test_http_url_partial_redaction():
"""URLs should have query params removed but keep path"""
import urllib.parse
for log in sample_logs:
if "http.url" in log:
parsed = urllib.parse.urlparse(log["http.url"])
# Should not contain query or fragment
assert not parsed.query, f"URL should not have query: {log['http.url']}"
assert not parsed.fragment, f"URL should not have fragment: {log['http.url']}"
def test_conditional_redaction_for_debug():
"""DEBUG logs should have additional redaction"""
debug_logs = [log for log in sample_logs if log["log_level"] == "DEBUG"]
for log in debug_logs:
# Check that potentially sensitive fields in context are redacted
if "request.body" in log:
assert log["request.body"] == "REDACTED" or \
"password" not in str(log["request.body"]).lower()
C. Cross-Field Validation Tests
python
def test_error_fields_consistency():
"""When log_level is ERROR/FATAL, error fields must exist"""
error_logs = [log for log in sample_logs
if log["log_level"] in ["ERROR", "FATAL"]]
for log in error_logs:
assert "error.type" in log
assert "error.message" in log
assert isinstance(log["error.type"], str)
assert isinstance(log["error.message"], str)
def test_trace_span_consistency():
"""If trace_id exists, span_id should also exist"""
for log in sample_logs:
if "trace_id" in log and log["trace_id"]:
assert "span_id" in log and log["span_id"]
def test_custom_field_naming():
"""Custom fields must follow naming conventions"""
for log in sample_logs:
for field in log:
if field.startswith("custom.") or field.startswith("metrics."):
# Should be lowercase alphanumeric with underscores
assert re.match(r'^[a-z0-9_.]+$', field), \
f"Invalid custom field name: {field}"
assert len(field) <= 64, \
f"Field name too long: {field}"
D. Integration Tests
python
def test_log_emission_with_sensitive_data():
"""Test that logging sensitive data automatically redacts"""
import logging
from logging_system import RedactingFormatter
logger = logging.getLogger("test")
handler = logging.StreamHandler()
handler.setFormatter(RedactingFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Capture output
with capture_logs() as captured:
logger.info("User login", extra={
"user.id": "12345",
"user.email": "test@example.com",
"request.body": {"password": "secret123"}
})
log_entry = parse_json(captured[0])
assert log_entry["user.id"] == "REDACTED"
assert log_entry["user.email"] == "REDACTED"
# request.body should be redacted or have password removed
assert "password" not in str(log_entry.get("request.body", ""))
def test_performance_impact():
"""Redaction should not add >5ms latency per log"""
import time
times = []
for _ in range(1000):
start = time.perf_counter()
log_with_sensitive_data()
times.append(time.perf_counter() - start)
avg = sum(times) / len(times)
assert avg < 0.005, f"Redaction too slow: {avg*1000:.2f}ms avg"
E. Compliance Tests
python
def test_no_pii_in_logs():
"""Verify no PII patterns appear in any field"""
pii_patterns = [
r'\b\d{3}-\d{2}-\d{4}\b', # SSN
r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b', # Credit card
r'\b\d{10}\b', # Phone number (simplified)
r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' # Email
]
for log in all_logs:
log_str = json.dumps(log)
for pattern in pii_patterns:
assert not re.search(pattern, log_str), \
f"Found potential PII in log: {log_str[:200]}"
def test_log_retention_compliance():
"""Verify logs don't contain data that should have been deleted"""
# For GDPR/CCPA: check for deletion timestamps, retention tags
for log in historical_logs:
assert "retention_days" in log or "data_category" in log
4. Implementation Guidelines
A. Logging Library Requirements
Automatic Redaction: Apply redaction rules at formatter level
Context Management: Support contextual logging (bind, unbind)
Performance: Redaction overhead < 5ms per log entry
# Check required fields
for field, meta in standard_fields.items():
if meta["required"]:
if field not in log_entry or log_entry[field] is None:
errors.append(f"Missing required field: {field}")
for key, value in log_entry.items():
# Standard field checks
if key in standard_fields:
meta = standard_fields[key]
# Type check
if meta["type"] == "string":
if not isinstance(value, str):
errors.append(f"Field {key} must be a string.")
# Allowed values
if "allowed_values" in meta and value not in meta["allowed_values"]:
errors.append(f"Field {key} must be one of {meta['allowed_values']}")
# Timestamp format
if key == "timestamp" and not is_valid_iso8601(value):
errors.append(f"Field {key} must be a valid ISO8601 string.")
# Sensitive field check
if key in sensitive_fields:
if not isinstance(value, str) or value != "REDACTED":
errors.append(f"Sensitive field {key} must be exactly 'REDACTED'")
return errors