Logging Best Practices: Structured Logs, Levels, Aggregation
Learn production logging with structured formats, useful log levels, correlation IDs, and scalable aggregation. Includes secure patterns for containerized apps.
Operational logs help teams reconstruct service behavior without collecting data they do not need. This guide covers log levels, trace context, structured fields, redaction, pipeline health, and retention. It separates diagnostic logs from authoritative audit records and shows how to estimate storage from measured event rates and record sizes.
Logging Best Practices: Structured Logs, Levels, and Aggregation
Introduction
When a checkout request fails, a stable request ID can connect the API response to a payment timeout and a retry in another service. Without consistent fields, responders search through unrelated messages and may miss the event that explains the failure. Logging the full request body can expose sensitive data, so useful context should be selected deliberately.
Good logging balances investigative value with latency, storage cost, privacy, and access risk. This guide covers event structure, correlation, collection, retention, and pipeline health for production systems. Pair it with metrics, monitoring, and alerting and distributed tracing to connect logs with broader service signals.
Log Levels
Log levels help filter noise. Not every log entry needs to be visible during normal operations.
Standard Log Levels
| Level | Purpose | When to Use |
|---|---|---|
| DEBUG | Detailed diagnostic information | During development and troubleshooting |
| INFO | Informational event | Service startup, completed request |
| WARN | Unexpected but handled situations | Recoverable errors, degraded states |
| ERROR | Errors that need attention | Failures that affect requests |
| FATAL | System cannot continue | Critical failures requiring immediate action |
Choosing the Right Level
This feels intuitive but gets harder at scale. A few guidelines:
- INFO for useful state changes, such as an order being accepted. These diagnostic logs can help explain service behavior, but they are not a substitute for an authoritative audit record.
- WARN for situations that require attention but the system continues: retries succeeded, cache misses, degraded mode.
- ERROR for failures that affect the current request: database timeout, external API failure, validation error.
- DEBUG for information that helps during development but would overwhelm production: loop iterations, intermediate values.
Use DEBUG selectively in production. Verbose records on a hot path can increase ingestion volume and compete for CPU, memory, and storage.
Trace Context and Correlation
When a request flows through multiple services, trace context lets you find the logs associated with its spans.
Propagating Trace Context
Use OpenTelemetry instrumentation to extract and inject W3C Trace Context across HTTP and messaging boundaries. The standard traceparent header carries the trace ID and parent span ID; application code should not invent a second header when the tracing library can propagate this context.
Attach the active span context to structured log records. The following is pseudocode; the logger or OpenTelemetry bridge obtains these values from the current request context:
logger.info("Request completed", {
service: "api-gateway",
trace_id: activeSpanContext.traceId,
span_id: activeSpanContext.spanId,
status_code: 200,
});
Database and message-queue instrumentation can use the same active context where supported. If a request has no active trace, leave trace_id and span_id absent rather than generating IDs that look like trace context.
OpenTelemetry defines TraceId and SpanId as optional log record fields. When a span ID is present, its data model recommends including the associated trace ID. See the OpenTelemetry logs data model and context propagation guide.
Searching by Trace ID
With structured logs and correlation IDs, debugging a user issue looks like this:
# Find all logs for a specific request
grep '"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"' /var/log/app.log
# Or in your log aggregator
query: trace_id = "4bf92f3577b34da6a3ce929d0e0e4736"
If each service records and exports the active trace context, a trace ID query can find related request, database, cache, and downstream-service logs that are still within retention.
What to Include in Logs
Include enough context to answer likely operational questions, while keeping sensitive fields out of the record. A stable schema makes filtering and correlation easier.
Essential Fields
For an OpenTelemetry-aligned JSON log, start with fields such as:
- timestamp: When the event occurred, recorded in UTC
- service: Which service produced the record
- trace_id and span_id: The active trace context, when present
- severity: The log level, such as
INFOorERROR - redaction_status: Whether the configured redaction policy ran for this record
- message: A short description of the event
Request Context
For web services, add only request attributes that are permitted by your privacy policy and useful for investigation. A route template such as /users/{user_id} is safer for aggregation than recording arbitrary raw paths.
{
"timestamp": "2026-11-22T08:45:12.456Z",
"service": "api-gateway",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7",
"severity": "INFO",
"redaction_status": "applied",
"message": "Request completed",
"http_method": "GET",
"http_route": "/users/{user_id}",
"status_code": 200,
"duration_ms": 120
}
redaction_status records whether the configured policy ran; it does not prove that every sensitive value was detected. Keep credentials, payment data, and other prohibited values out of logs, and drop or quarantine records if redaction fails.
Trace and request IDs can be useful fields in logs because responders often search for one request at a time. Keep high-cardinality values such as trace_id, request_id, and user_id out of metric labels. Metric storage tracks each distinct attribute combination, so unbounded IDs can create excessive time-series state. Use bounded dimensions such as service, status class, and route template for metrics. See OpenTelemetry metric cardinality guidance.
For web services, add permitted request attributes such as the HTTP method, route template, status code, and duration. Include a user or client identifier only when an operational need and privacy policy allow it; keep such high-cardinality values out of metric labels.
Business Events
For significant business events:
- Event type (login, purchase, registration)
- Entity IDs involved
- Outcome (success, failure)
- Duration if applicable
- Any relevant metadata
{
"timestamp": "2026-11-22T08:45:12.456Z",
"severity": "INFO",
"service": "checkout-service",
"message": "Order placed",
"redaction_status": "applied",
"event": "order_placed",
"order_id": "ord_xyz789",
"customer_id": "cust_123",
"total_amount": 99.99,
"currency": "USD",
"item_count": 3
}
Diagnostic Logs vs. Audit Records
Application logs help diagnose service behavior. They can be filtered or expired under an operational policy.
Audit records document security- or business-significant actions with a defined actor, action, target, outcome, and event time. They may need stricter access controls and tamper evidence. Generate authoritative records through the system of record or a dedicated audit pipeline; an INFO line saying “Order placed” does not prove that the order was committed.
What NOT to Log
Logging sensitive data creates security and compliance problems. Never log:
- Passwords or password hashes
- Credit card numbers or CVV codes
- Social security numbers or national IDs
- API keys or secrets
- Authorization tokens or fragments (use a request ID for correlation instead)
Redact Sensitive Data
function redactSensitiveFields(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(redactSensitiveFields);
}
if (value === null || typeof value !== "object") {
return value;
}
const sensitiveFields = ["password", "token", "secret", "creditCard", "ssn"];
const redacted: Record<string, unknown> = {};
for (const [key, fieldValue] of Object.entries(value)) {
if (sensitiveFields.some((f) => key.toLowerCase().includes(f))) {
redacted[key] = "[REDACTED]";
} else {
redacted[key] = redactSensitiveFields(fieldValue);
}
}
return redacted;
}
log.info(
"User authenticated",
redactSensitiveFields({ userId: "usr_123", password: "secret123" }),
);
// Logs: { userId: 'usr_123', password: '[REDACTED]' }
Log Aggregation Architecture
At scale, logs need to be collected, aggregated, and stored efficiently.
Common Architecture
graph LR
A[Application] -->|stdout/JSON| B[Container Runtime]
B --> C[Log Agent]
C --> D[Log Aggregator]
D --> E[Storage]
D --> F[Search Interface]
G[Analytics/BI] --> E
Container Logging
In containerized environments, applications write to stdout and stderr. The container runtime handles collection:
# Write logs to stdout, not files
# Bad: RUN echo "$(date) Log entry" >> /var/log/app.log
# Good: console.log(JSON.stringify({ timestamp, message }))
For applications that must write to files, use a sidecar log agent or mount a shared log directory:
# Pod with log volume
apiVersion: v1
kind: Pod
metadata:
name: myapp
spec:
containers:
- name: app
image: myapp:latest
volumeMounts:
- name: logs
mountPath: /var/log/myapp
- name: log-agent
image: log-agent:latest
volumeMounts:
- name: logs
mountPath: /var/log/myapp
- name: agent-config
mountPath: /etc/log-agent
volumes:
- name: logs
emptyDir: {}
- name: agent-config
configMap:
name: log-agent-config
Shipping Logs to Aggregators
Fluentd/Fluent Bit Configuration
# fluent-bit.conf
[SERVICE]
Flush 5
Daemon Off
Log_Level info
Parsers_File parsers.conf
[INPUT]
Name tail
Path /var/log/containers/*.log
Parser docker
Tag container.*
Refresh_Interval 5
[FILTER]
Name kubernetes
Match container.*
Kube_URL https://kubernetes.default.svc:443
Kube_CA_File /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
Kube_Token_File /var/run/secrets/kubernetes.io/serviceaccount/token
[OUTPUT]
Name es
Match container.*
Host elasticsearch.logging.svc
Port 9200
Logstash_Format On
Logstash_Prefix kubernetes
Retry_Limit False
Vector Configuration
Vector is a newer alternative with better performance and lower resource usage:
# vector.toml
[sources.docker]
type = "docker_logs"
[transforms.parse_json]
type = "remap"
inputs = ["docker"]
source = '.message = parse_json!(.message)'
[sinks.elasticsearch]
type = "elasticsearch"
inputs = ["parse_json"]
endpoint = "http://elasticsearch.logging.svc:9200"
index = "kubernetes-%Y.%m.%d"
Log Storage and Retention
Stored volume depends on event rate, record size, indexing, replication, and retention. Set a retention period for each log purpose, then measure the billable footprint against that policy.
Retention Tiers
| Tier | Retention choice | Use case |
|---|---|---|
| Searchable | Set from incident-response needs | Active troubleshooting and investigations |
| Archive | Keep only for a documented purpose | Required long-term retrieval |
| Deletion | Delete when the approved period expires | Data minimization and policy enforcement |
These are storage stages, not default time windows. Do not treat an operational log archive as an authoritative audit trail; audit records may have different integrity and retention requirements.
Illustrative Volume and Retention Estimate
Suppose one service emits an average of 100 records per second, and a representative serialized record is 1 kB (1,000 bytes). That is about 8.64 GB of raw log data per day. If the service’s documented operational policy keeps searchable logs for 14 days, the estimate is 8.64 GB × 14 = about 121 GB before compression, indexes, replicas, or metadata.
This is a planning example, not a provider price or a recommended retention period. Replace the event rate and record size with measurements from the service, then estimate cost with the provider’s current rates:
daily ingestion GB × ingestion price per GB
+ billable retained GB × storage price per GB
+ indexing, query, replication, and transfer charges that apply
The 14-day period applies only to this illustrative operational-log policy. Choose actual periods by record purpose, incident needs, and applicable obligations; store authoritative audit records under their own controls.
Elasticsearch Index Lifecycle Management
Elasticsearch Index Lifecycle Management (ILM) can roll over, move, and delete indices according to a policy. This example rolls over an index after seven days and deletes it seven days after rollover, for an approximately 14-day maximum from creation when the age trigger applies. If an index rolls over sooner, it is deleted sooner. Set the actual period from the service’s approved policy, and account for the fact that ILM measures min_age from rollover time after an index has rolled over (Elastic ILM documentation).
{
"policy": {
"phases": {
"hot": {
"actions": {
"rollover": {
"max_age": "7d"
},
"set_priority": 100
}
},
"delete": {
"min_age": "7d",
"actions": {
"delete": {}
}
}
}
}
}
Performance Considerations
Logging can become a bottleneck if you don’t design it carefully.
Asynchronous Logging
Write logs asynchronously so they don’t block your application:
import logging
import queue
from threading import Thread
class AsyncLogHandler(logging.Handler):
def __init__(self, batch_size=100, flush_interval=1.0):
super().__init__()
self.queue = queue.Queue(maxsize=10000)
self.batch_size = batch_size
self.flush_interval = flush_interval
self.worker = Thread(target=self._process_logs, daemon=True)
self.worker.start()
def emit(self, record):
try:
self.queue.put_nowait(self.format(record))
except queue.Full:
pass # Drop log if queue is full
def _process_logs(self):
batch = []
while True:
try:
item = self.queue.get(timeout=self.flush_interval)
batch.append(item)
while len(batch) < self.batch_size:
item = self.queue.get_nowait()
batch.append(item)
except queue.Empty:
pass
if batch:
self._send_batch(batch)
batch = []
def _send_batch(self, batch):
# Send to log aggregator
pass
Sampling High-Volume Logs
For debug-level logs in high-traffic paths, sample to reduce volume:
const sampler = new RateSampler({ rate: 0.1 }); // Illustrative sample rate only
log.debug(
{
message: "Processing item",
itemId: item.id,
sampled: sampler.sample(),
},
"Item processing details",
);
// Emits a sample of eligible debug events; choose the rate from measured volume.
Monitoring Log Health
Logs themselves need monitoring. If logging stops, you lose visibility into your systems.
Metrics to Track
Tracking the right metrics keeps your logging pipeline healthy and gives you early warning before small problems become incidents.
Log ingestion rate measures how many log events your system processes per second. A sudden drop to zero is the clearest signal something is wrong — either the application stopped logging, the agent stopped collecting, or the aggregator stopped accepting events. Set a baseline during normal operations and alert when you deviate significantly. Spikes in ingestion rate usually mean a developer accidentally pushed verbose DEBUG logging or an application is stuck in a retry loop generating excessive errors.
Log volume by service and level helps identify noisy services and sudden changes in logging behavior. Compare DEBUG volume with the information it adds, and check whether the current level policy is being followed. A spike can come from verbose configuration, retries, or an incident that produces more errors; investigate the source before dropping records.
Error rate in logs is your primary production health signal. You want the ratio of ERROR-level entries to total entries, tracked per service and over time windows. A rising error rate is often the first sign of a degradation that has not yet caused a full outage — a downstream service is slowing down, a dependency is returning partial responses, or a configuration drift is causing failures. Correlate error spikes with deployment times to catch bad releases quickly.
Log processing latency measures the time between an event being emitted and becoming searchable. Set an objective that fits your incident workflow and measure it end to end. When latency rises, responders may not find recent errors in the aggregator; check agent backpressure, network delays, and ingestion capacity.
Log agent errors and restarts matter because the log agent is infrastructure you forget exists until it breaks. Agents crash silently, run out of memory under load, or get OOM-killed by Kubernetes when the node is under pressure. When an agent restarts, there is a gap in coverage. Track restart counts and reason codes. If an agent restarts frequently, either increase its resource limits or reduce the log volume it handles.
Alert on Silence
# Prometheus alert for missing logs
- alert: LogIngestionSilence
expr: |
rate(fluentd_input_status_records_total[5m]) == 0
for: 5m
labels:
severity: critical
annotations:
summary: "No logs being ingested from Fluentd"
description: "Fluentd has not sent logs to Elasticsearch in 5 minutes"
When to Use Structured Logging
Use structured logging when:
- Debugging requires cross-referencing multiple log entries
- Requests span multiple services
- You need selective debugging in high-volume APIs
- You need consistent fields to correlate diagnostic logs with a separate audit-record system
- You need to correlate logs with traces or metrics
Don’t use structured logging when:
- Simple scripts or one-off utilities where stdout debugging suffices
- Very low-traffic applications where unstructured grep suffices
- Legacy systems where migration cost outweighs benefits
- Development environments where DEBUG-level verbosity is acceptable
Trade-Off Table
Structured Logs vs. Plain Text
| Aspect | Structured Logging | Plain Text Logging |
|---|---|---|
| Searchability | Field-level queries via log aggregators | grep/string matching only |
| Storage Cost | Depends on fields, encoding, compression, and indexing | Depends on message format and collector |
| Parse Complexity | Fields can be parsed directly | Depends on consistent formatting |
| Human Readability | Depends on field count and formatting | Often convenient in a terminal |
| Tooling Required | Structured-aware tools are useful | Basic text tools may suffice |
| Correlation | Shared fields can connect records | Requires a consistent context format |
| Performance Impact | Measure serialization and pipeline cost for the chosen logger | Measure formatting and collector cost |
Searchable Retention vs. Archive
| Choice | Advantages | Costs and limits | Use it for |
|---|---|---|---|
| Hot searchable index | Fast queries, dashboards, and incident triage | Can have higher storage and indexing costs; access needs tight controls | Recent operational events that responders query often |
| Warm or cold searchable tier | May reduce storage cost while retaining query access | Slower queries or fewer indexing features; test retrieval before an incident | Records needed for periodic investigations |
| Object storage archive | Lifecycle controls and separate long-term storage | Search may require restore or a separate query step; compare retrieval charges | Records kept for a defined long-term obligation or recovery purpose |
| Immutable or retention-locked archive | Helps prevent alteration or deletion during the retention window | Adds administration overhead and can make mistaken retention difficult to undo | High-integrity audit records with documented retention requirements |
Keep the fields responders need searchable for the period they are most likely to investigate. Move older records to another tier only after checking its storage and retrieval charges, that it preserves timestamps and schema context, and that the team can retrieve it within the required response time. Retention should follow a documented purpose and applicable policy; longer is not automatically safer.
SLI/SLO/Error Budget Templates for Logging
Log-Based SLI Template
# logging-sli-config.yaml
service: logging-observability
environment: production
slis:
- name: log_ingestion_success_rate
description: "Percentage of emitted logs successfully ingested"
query: |
sum(rate(log_ingested_total[5m]))
/
sum(rate(log_emitted_total[5m]))
- name: log_processing_latency_p95
description: "Time from log emit to searchable in aggregator"
query: |
histogram_quantile(0.95,
sum(rate(log_processing_latency_seconds_bucket[5m])) by (le)
)
- name: log_drop_rate
description: "Dropped logs as a percentage of emitted logs"
query: |
sum(rate(log_dropped_total[5m]))
/
sum(rate(log_emitted_total[5m])) * 100
Log SLO Template
# logging-slo-config.yaml
objectives:
- display_name: "Log Ingestion Availability"
sli: log_ingestion_success_rate
target: 99.5
window: 30d
description: "99.5% of emitted logs should be ingested"
- display_name: "Log Processing Latency"
sli: log_processing_latency_p95
target: 99.0
threshold_ms: 30000
window: 30d
description: "95% of logs should be searchable within 30 seconds"
Error Budget Calculator
# error-budget-calculator.py
def calculate_error_budget(slo_target, window_days=30):
"""
Calculate error budget in minutes for a given SLO target.
Example: 99.5% SLO over 30 days = 216 minutes (3.6 hours) of allowed errors
"""
window_seconds = window_days * 24 * 60 * 60
allowed_errors = window_seconds * (1 - slo_target)
return allowed_errors / 60 # Convert to minutes
# Standard SLO error budgets (30-day window)
slo_budgets = {
"99.0%": calculate_error_budget(0.990), # 432 minutes = 7.2 hours
"99.5%": calculate_error_budget(0.995), # 216 minutes = 3.6 hours
"99.9%": calculate_error_budget(0.999), # 43.2 minutes
"99.95%": calculate_error_budget(0.9995), # 21.6 minutes
"99.99%": calculate_error_budget(0.9999), # 4.32 minutes
}
for slo, budget in slo_budgets.items():
print(f"SLO {slo}: {budget:.2f} minutes error budget")
Multi-Window Burn-Rate Alerting for Log Ingestion
Burn-rate alerts detect when dropped logs consume the ingestion SLO’s error budget faster than expected. Use pipeline counters, not application ERROR log volume: an application can emit many errors while the logging pipeline is healthy.
1-Hour Window Burn-Rate Alert (Fast Burn)
# Burn-rate alerts for logging
groups:
- name: logging-burn-rate
rules:
# Fast burn: 1-hour window, 14.4x burn rate (burns 1% budget in 1 hour)
- alert: LogErrorBudgetFastBurn
expr: |
(
sum(rate(log_dropped_total[1h]))
/
sum(rate(log_emitted_total[1h]))
)
> (1 - 0.999) * 14.4
for: 5m
labels:
severity: critical
category: logging
window: 1h
annotations:
summary: "Log error budget burning fast (1h window)"
description: "Error rate is burning budget {{ $value | humanize }}x faster than sustainable. Budget may be depleted in ~7 hours."
6-Hour Window Burn-Rate Alert (Medium Burn)
# Medium burn: 6-hour window, 6x burn rate (burns 10% budget in 6 hours)
- alert: LogErrorBudgetMediumBurn
expr: |
(
sum(rate(log_dropped_total[6h]))
/
sum(rate(log_emitted_total[6h]))
)
> (1 - 0.999) * 6
for: 30m
labels:
severity: warning
category: logging
window: 6h
annotations:
summary: "Log error budget burning (6h window)"
description: "Error rate is burning budget {{ $value | humanize }}x faster than sustainable. Check for sustained error patterns."
Multi-Window Burn-Rate Alert Set
# Complete burn-rate alert set (multi-window)
- alert: LogErrorBudgetBurnAllWindows
expr: |
(
sum(rate(log_dropped_total[1h]))
/
sum(rate(log_emitted_total[1h]))
)
> (1 - 0.999) * 14.4
or
(
sum(rate(log_dropped_total[6h]))
/
sum(rate(log_emitted_total[6h]))
)
> (1 - 0.999) * 6
for: 5m
labels:
severity: critical
category: logging
annotations:
summary: "Log error budget burning across multiple time windows"
description: |
Multi-window burn-rate alert triggered.
The dropped-log ratio is above the multi-window burn-rate threshold.
Check agent buffers, exporter errors, and aggregator capacity.
SLO Error Budget Dashboard Panels
{
"dashboard": {
"title": "Logging SLO Error Budget",
"panels": [
{
"title": "Error Budget Remaining (30d)",
"type": "gauge",
"targets": [
{
"expr": "(1 - ((sum(rate(log_dropped_total[30d])) / sum(rate(log_emitted_total[30d]))) / (1 - 0.999))) * 100",
"legendFormat": "Budget Remaining %"
}
],
"fieldConfig": {
"defaults": {
"min": 0,
"max": 100,
"thresholds": {
"steps": [
{ "value": 0, "color": "red" },
{ "value": 50, "color": "yellow" },
{ "value": 90, "color": "green" }
]
}
}
}
},
{
"title": "Burn Rate (1h)",
"type": "graph",
"targets": [
{
"expr": "(sum(rate(log_dropped_total[1h])) / sum(rate(log_emitted_total[1h]))) / (1 - 0.999)",
"legendFormat": "Burn Rate"
}
]
},
{
"title": "Dropped Logs (1h)",
"type": "stat",
"targets": [
{
"expr": "sum(increase(log_dropped_total[1h]))",
"legendFormat": "Dropped log records"
}
]
}
]
}
}
OpenTelemetry Integration for Logging
OpenTelemetry provides APIs, SDKs, and exporters for traces, metrics, and logs. What is automatic depends on the language SDK and the libraries instrumented in the service. An OpenTelemetry Collector can route supported signals to configured backends, though changing backends may still require configuration or format mapping.
Auto-Instrumentation Setup
// OpenTelemetry collector configuration
import { NodeSDK } from "@opentelemetry/sdk-node";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter({
url: "http://otel-collector:4318/v1/traces",
}),
logRecordProcessor: new BatchLogRecordProcessor(
new OTLPLogExporter({
url: "http://otel-collector:4318/v1/logs",
}),
),
});
sdk.start();
Correlating Logs with Traces and Metrics
// Inject trace context into log records
import { trace, context } from "@opentelemetry/api";
function emitLog(level: string, message: string, attributes = {}) {
const span = trace.getSpan(context.active());
const record = {
timestamp: new Date().toISOString(),
severity: level,
message,
service: "checkout-service",
redaction_status: "applied",
trace_id: span?.spanContext().traceId,
span_id: span?.spanContext().spanId,
...attributes,
};
logger.emit(record);
}
Benefits of OpenTelemetry for Logging
| Benefit | Description |
|---|---|
| Vendor neutrality | Switch backends without re-instrumenting |
| Unified data model | Logs and traces can carry shared trace context; metrics use bounded dimensions |
| Context propagation | Configured instrumentation can inject trace context into logs |
| Sampling coordination | Coordinate trace and log sampling policies where the pipeline supports it |
Observability Hooks for Logging
This section defines what to log, measure, trace, and alert for logging systems themselves.
Log (What to Emit)
| Event | Fields | Level |
|---|---|---|
| Log ingestion started | service, host, agent_version | INFO |
| Log ingestion stopped | service, host, reason | WARN |
| Buffer approaching full | host, buffer_used_percent, buffer_limit | WARN |
| Malformed log detected | host, parse_error_type, sample | WARN |
| Retry attempt | host, destination, attempt, max_attempts | DEBUG |
| Batch sent successfully | host, destination, batch_size, bytes_sent | DEBUG |
| Authentication failure | host, client_ip, reason | WARN |
Measure (Metrics to Collect)
| Metric | Type | Description |
|---|---|---|
log_emitted_total |
Counter | Total logs emitted by service |
log_ingested_total |
Counter | Total logs ingested to aggregator |
log_dropped_total |
Counter | Logs dropped due to errors/full buffers |
log_processing_latency_seconds |
Histogram | Time from emit to searchable |
log_buffer_utilization_percent |
Gauge | Buffer fill percentage |
log_parsing_errors_total |
Counter | Malformed log entries |
log_bytes_sent_total |
Counter | Bytes sent to aggregators |
log_aggregator_queue_depth |
Gauge | Pending logs in aggregator queue |
Trace (Correlation Points)
| Operation | Trace Attribute | Purpose |
|---|---|---|
| Log emit | log.aggregate |
Track logs from emit through aggregation |
| Log parsing | log.parse.status |
Monitor parsing health |
| Log shipping | log.ship.destination |
Track delivery to aggregators |
| Batch processing | log.batch.size |
Monitor batch efficiency |
Alert (When to Page)
| Alert | Condition | Severity | Purpose |
|---|---|---|---|
| Log Silence | No logs received for 5 minutes | P1 Critical | Log pipeline failure |
| High Drop Rate | Drop rate > 1% for 5 minutes | P2 High | Pipeline health |
| Buffer Critical | Buffer > 90% full | P2 High | Prevent data loss |
| Parse Error Spike | Parse errors > 100/min | P3 Medium | Data quality |
| Latency High | Processing latency > 30s p95 | P3 Medium | Performance degradation |
Alerting Hook Template
# logging-observability-hooks.yaml
groups:
- name: logging-observability-hooks
rules:
# Alert on silence - no logs coming in
- alert: LoggingPipelineSilence
expr: rate(fluentd_input_status_records_total[5m]) == 0
for: 5m
labels:
severity: critical
annotations:
summary: "No logs being ingested (Alert on Silence)"
description: "Fluentd/Bit has not sent logs to Elasticsearch in 5 minutes. Either the log pipeline is down or all services have stopped logging."
# Alert on high drop rate
- alert: LoggingDropRateHigh
expr: |
sum(rate(fluentd_output_status_num_errors_total[5m]))
/
sum(rate(fluentd_input_status_records_total[5m])) > 0.01
for: 5m
labels:
severity: high
annotations:
summary: "Log drop rate above 1%"
description: "{{ $value | humanizePercentage }} of logs are being dropped. Check Fluentd/Bit error logs."
# Alert on buffer approaching full
- alert: LoggingBufferCritical
expr: fluentd_buffer_queue_length / fluentd_buffer_limit > 0.9
for: 5m
labels:
severity: high
annotations:
summary: "Log buffer above 90% capacity"
description: "Fluentd/Bit buffer is filling up. Risk of log loss if not addressed."
# Alert on high parsing errors
- alert: LoggingParseErrorSpike
expr: rate(log_parsing_errors_total[5m]) > 100
for: 5m
labels:
severity: warning
annotations:
summary: "High log parsing error rate"
description: "More than 100 parsing errors per minute. Review log format consistency."
# Alert on processing latency
- alert: LoggingProcessingLatencyHigh
expr: |
histogram_quantile(0.95,
sum(rate(log_processing_latency_seconds_bucket[5m])) by (le)
) > 30
for: 10m
labels:
severity: warning
annotations:
summary: "Log processing latency above 30 seconds"
description: "P95 log processing latency is {{ $value }}s. Logs may not be searchable in real-time."
# SLO error budget burn rate
- alert: LoggingErrorBudgetBurningFast
expr: |
(
sum(rate(log_dropped_total[1h]))
/
sum(rate(log_emitted_total[1h]))
) > (1 - 0.999) * 14.4
for: 5m
labels:
severity: critical
annotations:
summary: "Log error budget burning at unsustainable rate"
description: "Error budget is being consumed 14.4x faster than sustainable. Immediate investigation required."
Cost Optimization for Logging Pipeline
Measure ingestion, indexing, storage, and transfer by service before choosing a cost-control change.
Log Volume Budgeting
The quota values below are deployment-specific examples, not default capacity recommendations. Size them from observed log volume and agent resource use.
# Kubernetes resource quota for logging
apiVersion: v1
kind: ResourceQuota
metadata:
name: logging-budget
namespace: production
spec:
hard:
# Limit log storage per namespace
requests.storage: 100Gi
# Limit Fluentd memory
requests.memory: 2Gi
limits.memory: 4Gi
Cost Optimization Strategies
| Strategy | What to measure | Implementation |
|---|---|---|
| Reduce unnecessary DEBUG | Event count and value by level | Runtime level control or scoped debug settings |
| Index queried fields only | Index size and query latency | Review field mappings and search patterns |
| Apply lifecycle policy | Stored bytes and retrieval time by tier | Move or delete records at policy-defined points |
| Sample eligible debug logs | Retained volume and incident coverage | Use a documented sampling rule |
| Compress before shipping | CPU use and transmitted bytes | Compare agent settings under representative load |
Architecture for Cost-Effective Logging
graph TB
A[Application] --> B[Fluent Bit Agent]
B --> C{Local Buffer}
C --> D[Searchable storage: policy window]
D --> E[Archive: if required]
E --> F[Deletion: policy expiry]
egress costs in multi-region set-ups
Cross-region log shipping may incur transfer charges, depending on the provider and route. Check current provider rates and include transfer in the cost estimate. The Fluentd filter below is an example of dropping DEBUG and TRACE records before export; apply it only when those records are not needed for incident response or policy. Sampling is also a policy choice: preserve error and required security records unless the retention design handles them elsewhere.
# Fluentd filter to drop low-priority logs before shipping
<filter container.**>
@type grep
<exclude>
key level
pattern /DEBUG|TRACE/
</exclude>
</filter>
# Alternative: drop based on sampling
<filter container.**>
@type sampler
@label @sampled
sample_rate 0.1 # Example rate; tune from measured volume and coverage needs
random_seed 12345
</filter>
Multi-Region Logging Strategies
Global systems need log collection that respects regional boundaries and does not add latency to user-facing paths.
Regional Log Aggregation
When services run across multiple regions, centralizing logs can add transfer cost and affect query latency. Route logs to regional storage first when that fits the access and response needs, then send selected operational signals to a central cluster. Check provider pricing and retrieval behavior before choosing the path. The S3 sink config below illustrates routing logs by region.
# Regional Fluentd aggregator config
[sinks]
[sinks.s3_regional]
type = "s3"
bucket = "logs-us-east-1"
region = "us-east-1"
[sinks.s3_eu_central]
type = "s3"
bucket = "logs-eu-central-1"
region = "eu-central-1"
# Route logs to regional storage based on source
[transforms.route_by_region]
type = "route"
inputs = ["parse_json"]
route = '''
match /(?i)(eu|europe)/ => "s3_eu_central"
match * => "s3_regional"
'''
Cross-Region Log Correlation
Incidents that span regions may require querying more than one regional index. The TypeScript function below runs those queries in parallel, then keeps the returned log records together. Multiple records from one request share a trace_id, so do not use that field as a unique log-record key. If overlapping sources return duplicate copies, deduplicate by a stable record ID instead.
// Fan-out query across regions
async function searchLogsAcrossRegions(
query,
regions = ["us-east-1", "eu-central-1"],
) {
const results = await Promise.all(
regions.map((region) =>
elasticsearch.search({
index: `logs-${region}-*`,
body: {
query: {
bool: {
must: [query],
filter: [{ term: { region } }],
},
},
},
}),
),
);
// Preserve separate records; many records can share one trace_id.
return results.flatMap((r) => r.hits.hits);
}
Compliance Considerations
| Area | Consideration |
|---|---|
| Personal data and transfers | Minimize logged personal data, set purpose-based retention, and assess safeguards for international transfers. |
| Data residency | Use region-specific storage and access controls where residency obligations apply. |
| Audit integrity | Use immutable or tamper-evident retention for high-integrity records when policy or risk calls for it. |
| Incident response | Route only the events responders need to a central alerting index, subject to access and transfer controls. |
Cross-Region Replication Configuration
{
"index": {
"number_of_shards": 3,
"number_of_replicas": 1,
"allocation": {
"include": {
"region": "us-east-1"
}
}
},
"cluster.routing": {
"allocation.awareness.attributes": "region"
}
}
Production Failure Scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Log aggregation pipeline downtime | No new logs searchable; teams blind to issues | Buffer logs locally; implement retry with backoff; alert on pipeline health |
| Elasticsearch cluster saturation | Log ingestion backs up; logs dropped | Monitor ES cluster health; implement backpressure; use ILM to manage indices |
| Corrupted log data | Searches return incomplete results; debugging misses context | Validate JSON structure at ingestion; use dead-letter queues for malformed logs |
| Sensitive data logged | Security/compliance breach; potential data exposure | Implement redaction middleware; scan logs before storage; educate developers |
| Excessive log volume | Storage costs spike; performance degradation | Implement sampling for DEBUG logs; enforce log level policies; archive aggressively |
| Missing correlation IDs | Cannot trace requests across services | Auto-inject correlation IDs in middleware; reject requests without trace context in high-security paths |
Real-world Failure Scenarios
Scenario 1: Log Data Loss During Incident
What happened: During a production incident, engineers discovered that logs from the primary application server were not being shipped to the central log aggregator. The log forwarder had crashed silently 2 hours prior.
Root cause: No health checks were configured for the log forwarder daemon. The process had exited but the orchestration system did not restart it because it was running as a sidecar rather than a managed service.
Impact: Engineers spent 45 minutes manually accessing individual server logs to piece together the sequence of events, delaying incident resolution.
Lesson learned: Monitor log forwarder processes and shipper queues. Implement heartbeat logging so missing heartbeats trigger an alert. Ship logs to multiple destinations for critical services.
Scenario 2: Structured Logging Breaking Search Dashboards
What happened: After migrating from plain-text to structured JSON logging, the Kibana dashboard used by the operations team stopped displaying log events. The team was flying blind for 3 hours until the issue was diagnosed.
Root cause: The Kibana index pattern was configured to look for a message field as the primary text field. Structured logs used field names like msg and event_text, so no events matched the default search.
Impact: All monitoring dashboards showed empty results. A customer-impacting database slowdown went undetected for longer than necessary.
Lesson learned: Validate dashboard queries against a test environment before migrating logging formats. Ensure field naming conventions match across the log pipeline and dashboards. Maintain backwards compatibility during format transitions.
Common Pitfalls / Anti-Patterns
Anti-Patterns to Avoid
1. Logging Everything at DEBUG in Production
DEBUG-level logging in high-throughput services generates gigabytes per hour. Use sampling for debug scenarios, or enable DEBUG selectively via feature flags for specific request IDs.
2. Plain Text Logging with String Concatenation
// Bad: Cannot search, parse, or aggregate
logger.info("User " + userId + " purchased " + item);
// Good: Structured, searchable, aggregatable
logger.info("User purchased item", { userId, itemId, itemName, price });
3. Missing Trace Context Propagation
Logs without trace context can still be useful, but they are harder to connect across service boundaries. Use OpenTelemetry instrumentation to propagate W3C context through supported HTTP and messaging integrations, and attach the active trace_id and span_id to log records when available.
4. Logging Sensitive Data
Never log passwords, full tokens, credit card numbers, or PII. Implement redaction at the logger level, not the application level, to catch mistakes.
5. Synchronous Logging to Network Storage
Writing logs synchronously to a remote log server adds latency to every operation. Use async logging with local buffering and background shipping.
6. No Log Retention Policy
Without a retention policy, stored logs can accumulate beyond their operational value. Define searchable, archive, and deletion stages for each record purpose, then automate the lifecycle.
7. Logs as the Only Observability Signal
Relying solely on logs for debugging is insufficient at scale. Combine logs with metrics and traces for complete observability.
Observability Checklist
Key Log Metrics
- Log ingestion rate (logs/second) by service and level
- Log volume by service, level, and environment
- Error rate in logs (ERROR level count over time)
- Log processing latency (time from log emit to searchable)
- Log agent errors and restarts
- Storage utilization per index
Logs You Should Have
- Request logs with trace_id, span_id, method, route template, status, and duration_ms; include user identifiers only when permitted and needed
- Authentication events (login attempts, failures, token refreshes)
- Business events (orders, payments, registrations) with entity IDs
- Database query logs for slow queries (>100ms threshold)
- External API call logs with request/response timing
- Background job start/complete/fail logs with job IDs
- Health check and readiness probe logs
- Configuration change logs (who changed what when)
Alerts You Need
- No logs received from a service for >5 minutes (Alert on Silence pattern)
- Error rate spike above baseline (unexpected errors)
- Log volume anomaly (sudden drop or spike)
- Log processing latency >30 seconds
- Elasticsearch cluster health degraded (yellow/red)
- Log agent restart detected
Security and Compliance Notes
Treat logs as sensitive records: they can reveal identities, behavior, network details, and incident evidence. Decide which fields each team needs, redact or omit personal data at the source, and avoid copying request bodies or credentials into diagnostic events. Where correlation is necessary, use a request ID or a keyed, non-reversible identifier instead of a token value or token fragment.
Restrict log search and archive access by role, separate pipeline operators from retention administrators where practical, and record searches, exports, permission changes, and deletion attempts. Protect transport with TLS and use integrity controls for audit records, such as immutable retention or tamper-evident storage. These controls support an audit trail; they do not by themselves establish compliance. Set retention by record purpose, investigation needs, and applicable obligations, then test that retrieval, integrity checks, and approved deletion work as intended.
- No passwords, API keys, or secrets in log output
- Credit card numbers, CVV, SSN never logged
- Do not log authorization token values or fragments; use a request ID or keyed, non-reversible identifier when correlation is needed
- PII fields identified and redacted in redaction middleware
- Log access requires authentication and is audited
- Log aggregation pipeline uses TLS in transit
- Elasticsearch access restricted to authorized personnel
- Log retention complies with data retention policies
- Sensitive data cannot be searched in Kibana/ES by unauthorized users
Quick Recap Checklist
- Emit structured logs with consistent fields and severity levels.
- Propagate correlation IDs so a request can be followed across services.
- Redact secrets and sensitive personal or payment data before logs are written.
- Use sampling and retention policies to control volume and storage cost.
- Monitor ingestion, processing delay, storage health, and alert on silence.
Interview Questions
timeframe AND service.name: checkout-service AND "checkout failed". If no direct match, search for errors in the checkout service within the time window, then trace back via correlation IDs to find the root cause service.
doc_values: false on fields that are only used for filtering. Finally, enforce log volume budgets per service to prevent any single service from overwhelming the cluster.
traceparent header and create child spans from the active context.
metric.name: jvm_memory_used AND metric.area: heap AND increase(metric.value[1h]) > threshold. Set a PagerDuty alert when heap usage exceeds 80% sustained for 15 minutes or when the GC reclaim rate falls below the allocation rate. Correlate with your application logs to identify which code paths are allocating the most objects.
Further Reading
- Metrics, Monitoring & Alerting — Turn service signals into useful alerts.
- Distributed Tracing — Follow requests across service boundaries and connect spans with logs.
- Secrets Management — Protect credentials and sensitive values across backend systems.
- Fluentd Documentation — Official documentation for log aggregation.
- OpenTelemetry Logs specification — Vendor-neutral logging data model and SDK guidance.
- OpenTelemetry Logs Data Model — Defines timestamps, severity, and trace context fields.
- OpenTelemetry Context Propagation — Explains W3C trace context across service boundaries.
- OpenTelemetry Metrics Cardinality — Explains how attribute combinations affect metric cardinality.
- RFC 5424: The Syslog Protocol — Standard syslog message format.
Conclusion
Reliable logging starts with consistent fields, deliberate data boundaries, and a pipeline monitored like any other production dependency. Keep retention tied to operational needs and applicable obligations, and test that responders can retrieve the records they rely on.
Start with request context and ingestion health, then connect logs with metrics and traces as systems grow. The metrics, monitoring, and alerting guide and distributed tracing guide cover those complementary signals.
Category
Related Posts
Designing Production Alerts: Signals and Thresholds
Choose user-focused alert signals, set workload-specific thresholds, and use SLO burn rates without treating examples as universal defaults.
The Observability Engineering Mindset: Beyond Monitoring
Move beyond monitoring with structured logs, metrics, and traces. Learn how SLOs, sampling, OpenTelemetry, and team practices improve incident debugging.
Metrics, Monitoring, and Alerting: From SLIs to Alerts
Learn the RED and USE methods, SLIs/SLOs/SLAs, and how to build alerting systems that catch real problems. Includes examples for web services and databases.