Centralized Logging & Log Aggregation
Observability

Centralized Logging & Log Aggregation

A complete guide to Centralized Logging: structured JSON logs, log shippers (Fluent Bit, Logstash), Elasticsearch, Grafana Loki, and trace correlation.

When an application runs on a single server, troubleshooting an issue is simple: you connect over SSH, open `/var/log/app.log`, and run `tail -f`. The messages appear in your terminal, and you can spot the error right away. Now imagine your application consists of forty distinct microservices running across hundreds of temporary Docker containers on a Kubernetes cluster. When a user reports that their checkout failed, where did the error occur? Which specific container handled that user's request? And if that container crashed and was replaced by Kubernetes, its local log files on disk are completely gone. Centralized Logging solves this challenge. Instead of leaving log files isolated on temporary machines, centralized logging streams log entries from every container the moment they are generated, sends them to a central search system, indexes them, and allows engineers to search across all services from a single dashboard.

Definition

Centralized Logging is the practice of collecting, parsing, shipping, storing, and indexing log data from distributed applications and infrastructure into a unified search and analysis platform.

Why It Matters

In modern containerized environments, containers are ephemeral: when a pod terminates, its local filesystem is cleared. Without centralized log collection, valuable error details and audit records are lost permanently. Centralized logging gives engineering teams a single search interface to inspect, filter, and trace events across their entire fleet. It makes post-incident troubleshooting fast, satisfies security and regulatory compliance requirements (such as SOC2 and PCI-DSS), and enables developers to follow a single transaction as it travels across multiple services.

How It Works

Centralized logging works as an automated pipeline with four key stages: 1. Log Generation (Structured JSON Logging): Applications follow the Twelve-Factor App guideline: write logs directly to standard output (`stdout`) and standard error (`stderr`) as structured JSON objects (for example, including timestamp, log level, message, user ID, and trace ID). Structured JSON is easy for automated collectors to parse without brittle regular expressions. 2. Log Collection & Shipping (Agents): A lightweight agent runs on every server or Kubernetes node (often as a DaemonSet): • Fluent Bit or Vector: High-performance, lightweight log shippers written in C or Rust that consume minimal CPU and memory. They read container log files from the host node, enrich them with Kubernetes metadata (such as pod name, namespace, and container name), and stream them over the network. • Logstash: A flexible, feature-rich data processor that can parse and transform complex logs before forwarding them. 3. Storage & Indexing Engine: • Elasticsearch and OpenSearch (ELK Stack): Full-text search engines that index words within log messages into inverted indexes. They offer very fast search across large volumes of text, but require significant memory and disk storage. • Grafana Loki: A lightweight logging system inspired by Prometheus. Loki does not index the full text of logs; instead, it only indexes metadata labels (like `namespace=production` and `app=checkout`). The log text itself is compressed and stored cheaply in object storage (such as AWS S3), which significantly reduces infrastructure costs. 4. Visualization & Correlation: Engineers search and filter logs through web interfaces like Grafana or Kibana. By searching with a shared `trace_id` or `correlation_id` (passed through HTTP request headers), developers can see the complete timeline of a user's request across every microservice that handled it.

Centralized Logging Pipeline: Fluent Bit, Loki / Elasticsearch & Grafana

1. Container stdout/stderr
Applications print structured JSON directly to standard output without managing local files
2. Host Node Log Storage
The container runtime saves container outputs to node log paths such as `/var/log/pods/`
3. Fluent Bit DaemonSet
A lightweight agent on each node tails log files and enriches them with Kubernetes pod metadata
4. Network Streaming
Log batches are compressed and sent securely over encrypted connections to the central logging cluster
5. Storage & Indexing
Loki or Elasticsearch indexes metadata labels or text and stores log chunks reliably
6. Lifecycle Retention
Older logs transition across storage tiers: fast local storage to object storage, then long-term archives
7. Query Dashboards
Engineers search logs by service name, error code, or trace ID in Grafana or Kibana

Key Points

  • Applications should write logs to `stdout` and `stderr` instead of saving files to local container disks.
  • Always use structured JSON logging: plain string logs make automated filtering and search much more difficult.
  • Standardize log severity levels: DEBUG for local development, INFO for normal operations, WARN for unexpected but handled situations, and ERROR for faults requiring attention.
  • Correlate logs with distributed tracing using a shared `trace_id` to follow requests across microservice boundaries.
  • Mask or redact Personally Identifiable Information (PII) before sending logs to central storage to protect privacy.
  • Grafana Loki indexes metadata labels rather than full text, making it a very cost-effective choice for Kubernetes environments.

Steps

  1. Adopt Structured JSON Logging in Applications

    Use structured logging libraries (such as Pino, Winston, Zap, or Logback) to output JSON logs directly to standard output.

  2. Embed Distributed Trace Context

    Attach a unique `trace_id` or correlation ID to every incoming request and include it in all log statements for that request.

  3. Deploy Node-Level Log Collectors

    Deploy Fluent Bit or Promtail as a DaemonSet across your cluster to tail container logs from node filesystems.

  4. Set Up Central Storage and Retention Policies

    Direct log streams to Grafana Loki or OpenSearch, configuring lifecycle rules to archive or purge old logs automatically.

  5. Build Centralized Investigation Dashboards

    Create dashboards in Grafana or Kibana that allow engineers to filter logs by environment, namespace, level, and error code.

Examples

The Central Mail Sorting Facility Analogy

If every person in a large city tried to deliver mail directly to individual homes across town, streets would be chaotic and letters would get lost. Centralized logging works like a modern postal system: every application drops its standardized letters into standard output, mail trucks (Fluent Bit) collect them continuously, sorting facilities (indexing engines) organize them by address labels, and recipients (engineers in Grafana) can look up any message whenever needed.

Real-World Examples

End-to-End Request Tracing Across Microservices

In modern ride-sharing and food delivery platforms, a single customer order involves dozens of backend services, including location mapping, driver dispatch, pricing, and payment processing. By attaching a single correlation ID to the initial request, engineers can paste that ID into Grafana and view a chronological log of events from every involved service in one consolidated view.

Technical Examples

Fluent Bit Kubernetes Configuration for Structured Logging and Data Maskingyaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluent-bit-config
  namespace: logging
data:
  fluent-bit.conf: |
    [SERVICE]
        Flush         1
        Log_Level     info
        Daemon        off
        Parsers_File  parsers.conf

    # ── 1. INPUT: Tail all container logs from host ─────────────────
    [INPUT]
        Name              tail
        Tag               kube.*
        Path              /var/log/pods/*/*/*.log
        Parser            docker
        DB                /var/log/flb_kube.db
        Mem_Buf_Limit     50MB
        Skip_Long_Lines   On

    # ── 2. FILTER: Enrich logs with Kubernetes pod metadata ─────────
    [FILTER]
        Name                kubernetes
        Match               kube.*
        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
        Kube_Tag_Prefix     kube.var.log.pods.
        Merge_Log           On
        Merge_Log_Key       log_processed

    # ── 3. FILTER: Mask Sensitive Card Numbers (Data Redaction) ─────
    [FILTER]
        Name          modify
        Match         kube.*
        Condition     Key_Value_Matches log_processed.message [0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}
        Set           log_processed.message [REDACTED_CARD_NUMBER]

    # ── 4. OUTPUT: Stream to Grafana Loki ───────────────────────────
    [OUTPUT]
        Name          loki
        Match         kube.*
        Host          loki.logging.svc.cluster.local
        Port          3100
        Labels        job=fluentbit, namespace=$kubernetes['namespace_name'], app=$kubernetes['container_name']
This Fluent Bit configuration demonstrates standard log processing: it tails container log files on the host node, enriches each entry with Kubernetes pod metadata, scrubs sensitive payment card numbers before storage, and ships compressed streams to Grafana Loki.

Grafana Loki vs Elasticsearch / OpenSearch (ELK)

AspectGrafana LokiElasticsearch / OpenSearch (ELK)
Indexing ModelIndexes only metadata labels (similar to Prometheus)Builds full-text inverted indexes on entire log contents
Storage CostVery cost-effective; compresses and stores raw chunks in object storageHigher resource usage; requires more memory and dedicated SSD disks
Search CharacteristicsFast and lightweight on labeled streams and time windowsExtremely fast across broad, multi-month full-text searches
Operational FootprintLightweight and closely aligned with Prometheus and GrafanaRequires managing JVM memory, index shards, and lifecycle policies
Query LanguageLogQL (shares familiar syntax with PromQL)Elasticsearch Query DSL, Lucene, or KQL

Log Retention, Cost Governance and Privacy Protection

1. Sensitive Data Masking: Storing passwords, authentication tokens, or personal identifiers in plain-text logs creates legal and security risks. Use log shipper filters (such as Fluent Bit regex modifications) to detect and redact sensitive patterns before logs leave the host node. 2. Tiered Storage Lifecycles: • Hot Tier (Fast SSD Storage): 0 to 7 days. Designed for rapid search during active incident response. • Warm Tier (Object Storage): 8 to 30 days. Searchable with slightly higher latency for routine investigations. • Cold Tier (Archive Storage like S3 Glacier): 30 to 365 days. Highly compressed, encrypted storage retained for compliance and regulatory audits. 3. Log Level Hygiene: Avoid leaving verbose DEBUG logging enabled in production environments. Use configuration flags or environment variables so you can temporarily enable DEBUG mode when diagnosing an issue without rebuilding code.

Advantages

  • Consolidated Search: Search and filter logs from hundreds of containers in one place.
  • Resilient History: Preserves log data even when ephemeral containers or nodes restart.
  • Request Correlation: Follow the path of an individual user request through multiple microservices using a shared trace ID.
  • Audit and Compliance: Maintains reliable audit logs required by standards such as SOC2 and ISO 27001.

Limitations

  • Network and Storage Costs: High log volumes can consume significant network bandwidth and storage without careful filtering.
  • Query Overhead: Searching through unindexed full-text logs across very wide time windows can take longer without targeted label filters.

Interview Questions

How do you trace a single user request across multiple microservices using centralized logging?

You implement distributed tracing correlation. When an incoming request reaches your API gateway, generate a unique `trace_id` or `correlation_id`. Forward this ID across every service call using standard HTTP headers (such as `traceparent` or `X-Correlation-ID`). Configure the logging library in each microservice to include this ID in every structured log entry. When debugging, you can search for that specific `trace_id` in your logging dashboard to see a clean, chronological timeline of every log event produced across all services for that request.

Practice Questions

  1. Configure an application logger to output structured JSON format with fields for timestamp, severity level, message, and metadata.
  2. Write a simple LogQL query in Grafana to find all error logs from a specific application namespace over the past hour.