Skip to content
EgyKodeAcademy
Intermediate40 min

Centralized Logging (Fluentd/Loki)

After this chapter you can

  • Explain why Loki indexes labels and not log content

Introduction to Centralized Logging#

If an application crashes in a normal Linux server, you SSH into the server, run cat /var/log/syslog, and read the error message.

If an application crashes in Kubernetes, its Deployment (through the ReplicaSet it owns) replaces the Pod, and the new one takes its place. If you try to read the logs, they are gone forever. The error message is destroyed.

To fix this, we need Centralized Logging.


Level 1 — Beginner#

What is Centralized Logging?#

Imagine a company where 100 people are typing notes on their personal laptops. If someone's laptop breaks, their notes are lost. To fix this, the manager creates a rule: "Every time you type a sentence, you must instantly email a copy of that sentence to the main company server."

Now, if a laptop catches fire, the manager doesn't care. They just open the company server and read the emails.

In Kubernetes:

  • The Laptops: The Pods generating logs.
  • The Email Software: A log forwarding agent (like Promtail or Fluentd).
  • The Company Server: A centralized log database (like Loki or Elasticsearch).

ASCII Diagram: The Logging Pipeline#

text
[ Pod 1 ] --(prints to stdout)--> [ Node Log File ]
                                         |
                                         v
                                  [ Promtail Agent ]
                                         |
                                         v
                                  [ Grafana Loki ] (Central Database)
                                         |
                                         v
                                [ Grafana Dashboard ]

Level 2 — Intermediate#

How do Containers log?#

In Docker and Kubernetes, a container should NEVER write a log to a .txt file inside its own filesystem. The container must print all logs directly to Standard Output (stdout) and Standard Error (stderr).

When a container prints to stdout, the underlying Docker (or containerd) engine intercepts that text and saves it to a file on the Worker Node's hard drive (e.g., /var/log/containers/pod-name.log).

The DaemonSet Pattern#

How do we collect logs from 100 Worker Nodes? We use a DaemonSet. A DaemonSet is a special Kubernetes deployment that guarantees exactly one Pod runs on every single Worker Node. We run a Log Agent (like Promtail) as a DaemonSet. The Promtail Pod mounts the /var/log/containers folder from the Worker Node's hard drive. It reads every log file being generated by every other Pod on that node, and streams the text to the central database.


Level 3 — Advanced#

Analyzing the Logging Architecture (Loki vs. Elasticsearch)#

Historically, the industry standard was the ELK Stack (Elasticsearch, Logstash, Kibana) or the EFK Stack (Elasticsearch, Fluentd, Kibana). Elasticsearch is a full-text search engine. It creates a massive index of every single word in every single log line. If your logs say Connection Refused, Elasticsearch indexes the word Connection and the word Refused.

The Problem: Indexing every word takes an insane amount of CPU and RAM. For a large Kubernetes cluster, the Elasticsearch cluster can cost $10,000 a month in AWS EC2 fees alone.

The Solution: We use Grafana Loki. Loki was built explicitly for Kubernetes. It is inspired by Prometheus. Loki does NOT index the text of the logs. It only indexes the labels (e.g., namespace="production", app="ivolve-api"). The actual raw text of the logs is compressed into chunks and sent straight to cheap AWS S3 storage. When you search for Connection Refused, Loki uses the labels to instantly find the correct chunk of logs, uncompresses it, and uses brute-force grep to find the text.

Because Loki doesn't index the text, it uses 90% less RAM than Elasticsearch, saving the company massive amounts of money.

LogQL (Loki Query Language)#

Because Loki is built by Grafana, you search logs using a language that looks exactly like PromQL. To find all logs from the API that contain the word "Error": {app="ivolve-api"} |= "Error"


Level 4 — Enterprise#

Enterprise Patterns: Structured Logging (JSON)#

If your application prints this log: 2026-05-12 14:02:11 ERROR Failed to login user 12345

It is very difficult for a machine to parse that. If the developer changes the text to User 12345 failed to login, your alerts will break.

In an Enterprise, developers are forced to use Structured Logging. Applications must output logs exclusively in JSON format. {"time": "2026-05-12T14:02:11Z", "level": "error", "event": "login_failed", "user_id": 12345}

The Log Agent (Fluentd/Promtail) can easily parse this JSON, allowing DevOps engineers to write precise queries without worrying about developers changing sentence structures.

Log Masking (PII / PCI Compliance)#

If an application accidentally prints a customer's Credit Card number or Social Security Number in a log, and that log is sent to a central database, your company has committed a massive security breach and will be fined millions of dollars.

You must configure your Log Agent to mask data. In Fluentd or Promtail, you use a Regex pipeline stage before the log is sent over the network:

yaml
pipelineStages:
  - match:
      selector: '{app="payment"}'
      stages:
      - replace:
          expression: '(?:\d{4}-){3}\d{4}'
          replace: '****-****-****-****'

This intercepts the log stream, finds any 16-digit credit card pattern, and overwrites it with asterisks before it ever reaches Loki.


Interview Questions#

Beginner#

Q: Why can't we just use kubectl logs <pod> in a production environment? A: kubectl logs only reads the logs that are currently on the Worker Node's hard drive. If the Pod crashes, scales down, or the Node itself dies, the logs are permanently deleted. You need a centralized system to store the logs off the cluster.

Intermediate#

Q: What is a DaemonSet and why is it used for logging? A: A DaemonSet ensures that exactly one copy of a Pod runs on every single node in the cluster. Because logs are generated by applications on every node and saved to that specific node's local hard drive, you need a Log Agent running on every single node to read those local files.

Senior#

Q: Explain the architectural difference between Loki and Elasticsearch, and why Loki is more cost-effective for Kubernetes. A: Elasticsearch is an inverted index search engine; it indexes every word of every log line, which requires massive compute and RAM, often making the logging cluster more expensive than the actual application cluster. Loki only indexes the metadata labels (like the Kubernetes namespace and pod name), leaving the actual log text unindexed and compressed in cheap object storage (S3). It trades query speed for massive ingestion efficiency and cost reduction, which aligns perfectly with Kubernetes label architectures.

Principal/Architect#

Q: Your enterprise ingests 10 Terabytes of logs per day into Splunk/Elasticsearch, costing millions. 80% of these logs are useless "INFO" debug messages, but compliance requires you to store them for 7 years. How do you architect a pipeline to reduce costs without violating compliance? A: You implement a Log Routing/Observability Pipeline (using tools like Vector, FluentBit, or Cribl LogStream) before the logs reach the expensive SIEM/Search database. The pipeline uses dynamic routing rules:

  1. High-value logs (ERROR, WARN, Security Events) are routed to the expensive Elasticsearch/Splunk cluster for real-time querying by engineers.
  2. Low-value logs (INFO, TRACE, DEBUG) are stripped of unnecessary JSON whitespace and routed directly to a cheap AWS S3 bucket (or Glacier) in Parquet format. You satisfy the 7-year compliance requirement for pennies, while drastically reducing the license and compute costs of your primary logging database. Contents | DevSecOps (Container Security) |

Practise it

Check yourself

4 questions from this chapter. Try answering before you look.

  • Why can't we just use `kubectl logs <pod>` in a production environment?
  • What is a DaemonSet and why is it used for logging?
  • Explain the architectural difference between Loki and Elasticsearch, and why Loki is more cost-effective for Kubernetes.
  • Your enterprise ingests 10 Terabytes of logs per day into Splunk/Elasticsearch, costing millions. 80% of these logs are useless "INFO" debug messages, but compliance requires you to store them for 7 years. How do you architect a pipeline to reduce costs without violating compliance?
Questions from the curriculum →

Recommended free courses

All courses

Another way to learn this — external, free, and not affiliated with EgyKode.