Production-grade guide to log aggregation patterns covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Log aggregation consolidates logs from multiple services, hosts, and environments into a unified system for search, analysis, and alerting. It matters when systems span microservices, containers, or cloud infrastructure—when logs are scattered across hundreds of machines, and troubleshooting requires stitching together events across services. This page describes the core patterns engineers use to build and evolve reliable log aggregation systems, focusing on what they do, why it works, and where it breaks.
The foundation of any log aggregation system is the movement of log data from its source to a central storage. The goal is to collect all logs—application, system, container, and platform—into a single, searchable repository.
The most common approach uses agents that run on each host or container. These agents tail log files, read from standard output, and forward data via a lightweight protocol. A typical setup involves deploying a daemon process that monitors log files, emits structured JSON, and sends batches to a central server.
# /etc/systemd/system/log-agent.service
[Unit]
Description=Log Aggregation Agent
After=network.target
[Service]
ExecStart=/usr/bin/log-agent --input /var/log/app/*.log --output http://logging.example.com/api/v1/logs --batch-size 1000 --timeout 30s
Restart=always
User=log-agent
Group=log-agent
[Install]
WantedBy=multi-user.target
The agent must handle edge cases: log file rotation (where logrotate moves app.log to app.log.1 and creates a new app.log), incomplete writes, and network outages. During network failure, agents buffer logs locally—typically in a circular buffer or on-disk queue—before retrying uploads.
The standard HTTP-based ingestion API expects structured JSON payloads with a consistent schema:
{
"timestamp": "2024-05-12T08:37:12.456Z",
"level": "INFO",
"source": "web-service",
"host": "web-01.example.com",
"message": "User login succeeded",
"fields": {
"user_id": 12345,
"session_id": "abc123xyz",
"ip": "192.168.1.10"
}
}
When the ingestion endpoint returns a 429 Too Many Requests or 503 Service Unavailable, agents must back off exponentially and persist batches to disk. On restart, they resume from the last acknowledged offset—often tracked via an ack token or offset field in the response.
A common failure mode is log duplication: when the agent restarts, it reprocesses logs from the previous checkpoint, causing the same event to appear twice. This happens when the agent fails to persist the last processed offset before shutdown, or when the central system acknowledges a batch before the agent commits the file position.
Before aggregating logs, systems must emit structured data. Raw text logs—like INFO: User login succeeded—are inadequate for analysis. Engineers must define and enforce a consistent structure.
The most effective approach uses a logging library that supports structured fields. In a Go service, this might look like:
logger.Info("User login succeeded",
"user_id", userID,
"session_id", sessionID,
"ip", ip,
"duration_ms", duration.Milliseconds(),
)
This produces logs in JSON format:
{
"timestamp": "2024-05-12T08:37:12.456Z",
"level": "info",
"message": "User login succeeded",
"user_id": 12345,
"session_id": "abc123xyz",
"ip": "192.168.1.10",
"duration_ms": 124
}
The structure enables filtering, aggregation, and alerting. A query for level=ERROR AND duration_ms > 1000 returns logs where a service took longer than a second.
A key failure mode is field inconsistency: different services use slightly different keys for the same concept. One service logs "user_id", another "userId", and a third "user-id". The aggregation system must normalize these fields, typically using a mapping configuration.
# Standard field mapping
field_mapping:
user_id: ["user_id", "userId", "user-id"]
session_id: ["session_id", "sessionId", "session-id"]
duration_ms: ["duration_ms", "durationMs", "duration-ms"]
host: ["host", "hostname", "machine"]
This mapping is applied during ingestion or at query time. Without it, analysts cannot correlate logs across services.
Raw logs often lack context. Enrichment adds metadata—like environment, service version, or cluster name—before aggregation.
This is achieved through preprocessing pipelines, often implemented as a sequence of transformations applied to each log entry. The pipeline might run in a stream-processing system like Kafka or as a series of stages in a log agent.
A common preprocessing step is source tagging. The agent adds a source field based on the service name derived from the log file path:
# /var/log/web-service/app.log → source=web-service
# /var/log/payment-service/api.log → source=payment-service
Another step is timestamp normalization. Logs may have local timestamps with timezone offsets, but the aggregation system expects UTC. A preprocessing function converts all timestamps to UTC and adds a timezone field.
{
"timestamp": "2024-05-12T08:37:12.456+02:00",
"level": "INFO",
"message": "User login succeeded",
"timezone": "Europe/Berlin"
}
The system then applies timestamp = convert_to_utc(timestamp) and updates the field.
A subtle failure occurs when multiple sources contribute to the same log stream. For example, a service writes logs to /var/log/app.log, but also emits structured logs via a logging library to stdout. The log agent captures both, but without deduplication, the same event appears twice—once from app.log, once from stdout.
To solve this, the preprocessing pipeline includes duplicate detection using a composite key: source, timestamp, message, and fields. Two entries with identical keys are merged, with the one having the most fields taking precedence.
With logs from many sources, the aggregation system must support efficient querying across all data. This requires indexing the logs by common fields: source, level, timestamp, and fields.
Indexing is typically built on top of a search engine. The system ingests logs into an index, which is a data structure optimized for full-text search and filtering.
Each log entry is stored as a document, with fields indexed in a B-tree or inverted index. The system supports queries like:
source=web-service AND level=ERRORmessage CONTAINS "failed to connect"fields.user_id = 12345 AND timestamp > "2024-05-12T00:00:00Z"A common failure mode is index misalignment: when the index is built using a different schema than the data. For example, the fields.user_id field is indexed as user_id, but the ingestion pipeline writes userId. The query fields.user_id = 12345 returns no results.
The solution is to define a schema registry that maps field names to index keys. This registry is applied at ingestion time:
{
"schema": {
"user_id": "fields.user_id",
"session_id": "fields.session_id",
"duration_ms": "fields.duration_ms"
}
}
When a new field is added—fields.request_id—the system must update the schema and reindex all historical data.
Log aggregation systems must handle data growth. Over time, logs accumulate, and storage becomes expensive. Retention policies define how long logs are kept and how they are moved between storage tiers.
The system uses a tiered storage model: hot, warm, and cold storage. Hot storage holds recent logs (e.g., last 7 days) in fast, expensive storage (SSD, in-memory). Warm storage (HDD, cloud object storage) holds logs from 7 to 30 days. Cold storage (archive, tape, S3 Glacier) holds logs older than 30 days.
Retention is managed via a lifecycle policy:
lifecycle:
- days: 7
storage: hot
retention: "7 days"
compression: "zstd"
- days: 30
storage: warm
retention: "30 days"
compression: "gzip"
- days: 365
storage: cold
retention: "1 year"
compression: "lz4"
The policy is applied automatically by a background job that moves logs between tiers based on age.
A failure mode is retention drift: logs are not moved to the next tier on time. This occurs when the job fails to update the last_moved timestamp or when the storage system returns a transient error. Logs remain in cold storage for years, but are not accessible during peak query windows.
Another failure is indexing latency: queries on newly ingested logs return stale results. The system must ensure that the index is updated in real time. One approach is to use incremental indexing: each batch of logs is indexed immediately, and a nightly job builds a full index from all data.
Once logs are aggregated and indexed, engineers use them to explore system behavior. The most common interface is a query language.
A typical query might look like:
SELECT *
FROM logs
WHERE source = 'payment-service'
AND level = 'ERROR'
AND timestamp >= '2024-05-12T08:00:00Z'
ORDER BY timestamp DESC
LIMIT 100
The system supports filtering, aggregation, and grouping:
SELECT
source,
COUNT(*) AS error_count,
AVG(fields.duration_ms) AS avg_duration,
MAX(fields.error_code) AS max_error_code
FROM logs
WHERE level = 'ERROR'
AND timestamp >= '2024-05-12T08:00:00Z'
GROUP BY source
ORDER BY error_count DESC
A subtle failure is field projection mismatch: a query selects fields.user_id, but the index only contains user_id (not fields.user_id). The field is not found, and the query returns null for user_id.
The solution is to define field projections at query time:
{
"projection": {
"user_id": "fields.user_id",
"session_id": "fields.session_id",
"duration_ms": "fields.duration_ms"
}
}
This ensures that the query engine maps the projected fields correctly.
Log aggregation systems fail in subtle ways. Common failure modes include:
To detect these, the system must expose monitoring metrics:
ingestion_latency: time from log generation to index availabilityduplicate_rate: percentage of logs with duplicate timestamp and messageindexing_rate: logs indexed per secondretention_job_success_rate: percentage of retention jobs that complete successfullyThese metrics are monitored via a dashboard, with alerts triggered on anomalies. The system also logs its own health—agent logs, index metadata, and retention job logs—into the same aggregation system, enabling self-observability.
The final pattern is log-driven incident response: engineers use the log aggregation system as the primary tool to investigate issues. They start with a query, drill down into specific events, and correlate logs across services. This becomes the default workflow for on-call engineers.
This page was rewritten on 17 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy