Course contents · Lesson 11 of 22

Log Aggregation and Retention Explained

Logs · Lesson 11 of 22 · 11 min Engineer

At 2 a.m. the checkout service starts failing for some users. It runs as 40 containers spread over 12 servers, and the pod that was failing has already been replaced, so its logs were deleted with it. Logging in to each server in turn would take an hour you do not have. Log aggregation solves this: every machine sends its logs to one central place, where you can search all of them at once, including lines from containers that no longer exist.

Why logs need one central place

In What Are Logs? you read logs on one machine with docker logs and journalctl. That stops working as systems grow, for three reasons:

  • Machines are short-lived. Containers are replaced on every deploy, and cloud servers are removed when traffic drops. Logs stored on them vanish with them.
  • Searching host by host does not scale. One request may touch five services on five machines, and you need all of their lines side by side, in time order.
  • Access is risky. Giving every engineer a login on every production server just to read logs is a security problem. A central tool can control who sees what.

So log aggregation means collecting logs from every source into one system that stores, indexes and searches them. Common examples are the Elastic Stack (Elasticsearch and Kibana), OpenSearch, Grafana Loki, Splunk and cloud services such as Amazon CloudWatch Logs.

The pipeline: collect, ship, parse, store, search

Every aggregation system follows the same five steps, even when one product does several of them:

  1. Collect. An agent, a small program on every machine, reads new lines from log files or journald. On Kubernetes it runs as a DaemonSet, which places one copy on every node.
  2. Ship. The agent sends lines over the network, buffering them when the destination is slow so a short outage loses nothing.
  3. Parse and enrich. JSON lines are split into fields, plain text is cut up with patterns, and context is added: host, pod, namespace, environment.
  4. Store and index. The store writes lines to disk and builds an index, a lookup structure that finds matching lines without reading them all.
  5. Search and alert. A web UI such as Kibana or Grafana queries everything at once, and alert rules can notify someone when a pattern appears.
Flowchart: three nodes with apps and agents send lines to a ship and parse stage, then to a central store that feeds search and alerts, with older data moving to a cheap archive
Because the agent ships lines while a node is alive, the replaced node's logs are still in the central store after the node itself is gone.

Popular agents include Fluent Bit, Vector, Grafana Alloy and the OpenTelemetry Collector. Here is a minimal Fluent Bit configuration for a Kubernetes node. It tails the container log files, adds Kubernetes details and sends everything to Loki:

[INPUT]
    Name              tail
    Path              /var/log/containers/*.log
    multiline.parser  docker, cri
    Tag               kube.*

[FILTER]
    Name       kubernetes
    Match      kube.*
    Merge_Log  On

[OUTPUT]
    Name    loki
    Match   *
    Host    loki.monitoring.svc
    Port    3100
    Labels  job=fluent-bit

The multiline.parser line understands both container log formats, Docker's and the CRI format used by containerd. The kubernetes filter adds each line's pod name, namespace and labels. Merge_Log On turns a JSON log line into top-level fields, the payoff of structured logging.

Retention: how long to keep logs

Retention is how long you keep logs before deleting them. Keeping everything forever sounds safe, but the bill grows every day. If your services write 50 GB of logs a day, 30 days of retention is about 1.5 TB of indexed data before replicas, and a year is about 18 TB.

Illustrative chart: the value of a log line falls steeply with age while the cost of keeping it in hot storage stays flat, leaving a shaded area where storage costs more than the line is worth
A line is worth most in its first days, but hot storage charges the same every day, so after a short time you are paying more than it is worth.

Most of that data is rarely read, because nearly every search looks at the last few hours or days. So stores use storage tiers. Hot holds recent logs on fast, expensive disks, searchable in seconds. Warm holds older logs on cheaper hardware. Cold or archive holds old logs in cheap object storage such as Amazon S3, slow to search and sometimes needing a restore first. After the last tier, logs are deleted.

Timeline of retention tiers: hot from day 0 to 7, warm from day 7 to 30, cold or archive from day 30 to 365, then delete
Each tier trades search speed for a lower price, so a line slides to cheaper storage as the chance that anyone needs it drops.

Elasticsearch expresses tiers as an index lifecycle management (ILM) policy. This one matches the timeline above:

PUT _ilm/policy/app-logs
{
  "policy": {
    "phases": {
      "hot":    { "actions": { "rollover": { "max_age": "1d", "max_primary_shard_size": "50gb" } } },
      "warm":   { "min_age": "7d",   "actions": { "forcemerge": { "max_num_segments": 1 } } },
      "cold":   { "min_age": "30d",  "actions": { "set_priority": { "priority": 0 } } },
      "delete": { "min_age": "365d", "actions": { "delete": {} } }
    }
  }
}

Each phase starts at its min_age, counted from the moment the index rolled over to a fresh one. If the cluster has warm and cold nodes, Elasticsearch moves the data onto them automatically. Loki is simpler: it usually keeps everything in object storage and deletes data older than its retention_period. Rules outside engineering can set the numbers, too. The PCI DSS card-payment standard requires 12 months of audit logs, with three months immediately available, while privacy laws push you to delete personal data once you no longer need it.

Log rotation on a single machine

On each server, a log file left alone grows until the disk is full. Log rotation prevents that: on a schedule or when a file gets too big, the current file is renamed (app.log becomes app.log.1), older copies are compressed (app.log.2.gz) and the oldest are deleted. On Linux the usual tool is logrotate, run once a day by a systemd timer or cron. A rule for one app:

/var/log/myapp/*.log {
    daily
    rotate 14
    maxsize 100M
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}

This rotates daily, or sooner if a file is over 100 MB when logrotate runs. It keeps 14 old copies and compresses all but the newest. copytruncate copies the file and then empties it, so the app can keep writing to the same open file. A few lines can be lost in that gap, which is why nginx's packaged rule renames the file and signals nginx to reopen it instead. Test any rule with logrotate -d /etc/logrotate.d/myapp, which shows what would happen without doing it.

Two other places need limits too. journald caps its size with SystemMaxUse= in /etc/systemd/journald.conf, and journalctl --disk-usage shows its current size. Docker's default json-file driver never rotates unless you set max-size and max-file in /etc/docker/daemon.json, a common cause of full disks. On Kubernetes, the kubelet rotates container logs at 10 MiB by default.

Controlling volume and risk

Every line you ship costs network, storage and often licence money, since many log platforms charge by gigabytes ingested per day. Three controls keep volume and risk down:

  • Drop noise. Filter out DEBUG lines and repetitive successes, such as a load balancer's health checks hitting /healthz every few seconds.
  • Redact personal data. Remove or mask fields such as email addresses before they reach a store that many people can search.
  • Set quotas. Give each team an ingestion limit, so one service stuck in an error loop cannot flood the store, or the bill, for everyone.

The first two belong in the agent, before lines leave the node. In Fluent Bit they are two more filters: grep with Exclude drops records whose field matches a pattern, and modify with Remove deletes a field:

[FILTER]
    Name     grep
    Match    kube.*
    Exclude  level ^debug$

[FILTER]
    Name     modify
    Match    kube.*
    Remove   email

Quotas usually live in the store: Loki, for example, has per-tenant ingestion rate limits, and hosted services let you cap daily volume. Together these controls keep central logging affordable, so nobody is tempted to switch it off.

Check yourself

Kubernetes replaced a crashing pod an hour ago. Why might its logs be gone without aggregation?

Container logs live on the node beside the pod and are deleted with it; only an agent that already shipped them keeps a copy.

Why not keep every log line in the hot tier for a year?

Hot storage is the most expensive tier, and almost all searches hit recent data, so old lines there cost more than they are worth.

What does copytruncate in a logrotate rule trade away?

It lets the app keep its file open with no restart or signal, at the risk of losing the few lines written between the copy and the truncate.