> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Logging for Platforms Patterns That Scale

> Designing scalable centralized logging in Kubernetes with structured JSON logs, collection patterns, storage choices, and trace ID integration for fast troubleshooting.

We've already covered metrics and traces. This lesson covers the third observability pillar: logging.

Quick summary: metrics tell you what happened, traces tell you where it happened, and logs tell you why it happened.

By the end of this lesson you'll understand why [`kubectl logs`](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs) breaks at scale, what structured logging looks like, how a production logging pipeline is built, and how trace IDs let you jump from logs into traces.

A real-world example: a company runs 350 pods across two clusters. An escalation arrives for an error that occurred six hours earlier. The affected pods restarted twice and their local logs are gone. [`kubectl logs --previous`](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs) doesn't help because the pod was rescheduled to another node. Ninety minutes of triage later, no root cause. After a centralized logging pipeline is in place, the same investigation takes ≈8 seconds.

![An infographic titled "Kubectl Logs Doesn't Scale" that contrasts a red "Before: No Central Logging" column of logging problems with a green "After: Centralized Logging" column showing the solution. The after column lists Fluentd → Elasticsearch → Kibana for centralized logs across all pods/namespaces with 30‑day retention and fast (≈8s) search.](https://mintcdn.com/kodekloud-c4ac6d9a/seqLTE3JlSrVAtw9/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Observability-and-Operations/Logging-for-Platforms-Patterns-That-Scale/kubectl-logs-doesnt-scale-infographic.jpg?fit=max\&auto=format\&n=seqLTE3JlSrVAtw9\&q=85\&s=e3d356371b751c7b7149b83096dc53e7)

## What breaks at scale

* Pod logs are ephemeral. Pods crash, get evicted, or are rescheduled and local logs disappear.
* There is no simple way to search across pods or correlate events between services without a central store.
* Critical logs (the ones you need for troubleshooting) often vanish first.

What you need instead: persistent storage, centralized search, structured logs, and correlation IDs. Those are the core benefits of a logging pipeline; structured logging is the foundation.

## Structured vs. unstructured logs

Unstructured logs are plain text designed for humans. They look fine in a terminal, but machines struggle with them: parsing fields reliably often requires fragile regular expressions.

Example unstructured log:

```text theme={null}
2024-03-15 14:32:01 ERROR PaymentSvc Failed to process payment for user 4821 - timeout after 5000ms
```

Structured logs (JSON) give every field a name and a type, which makes downstream processing reliable and fast:

```json theme={null}
{
  "ts": "2024-03-15T14:32:01Z",
  "level": "error",
  "service": "PaymentSvc",
  "msg": "Payment failed",
  "user_id": 4821,
  "duration_ms": 5000,
  "trace_id": "abc-123-def-456"
}
```

Note the `trace_id` field — this is how logs connect back to traces. With trace IDs available in logs, you can find an error log and jump to the corresponding [Jaeger](https://www.jaegertracing.io/) trace waterfall if your tools are integrated.

Benefits of structured JSON logs:

* Machine-parseable — no fragile regexes.
* Filterable — run precise queries such as `level="error" AND user_id=4821`.
* Aggregatable — count errors per service.
* Correlatable — follow a single ID across logs, traces, and metrics.

The split of responsibility is clear: applications should emit JSON to stdout/stderr; the platform team collects, enriches, stores, and serves the logs.

![A presentation slide titled "Structured Logging: JSON as Standard" that lists five benefits with icons: Machine-Parseable, Filterable, Aggregatable, Correlatable, and Consistent. A footer rule reads that applications should log to stdout in JSON while the platform handles collection, shipping, and storage.](https://mintcdn.com/kodekloud-c4ac6d9a/seqLTE3JlSrVAtw9/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Observability-and-Operations/Logging-for-Platforms-Patterns-That-Scale/structured-logging-json-stdout-benefits.jpg?fit=max\&auto=format\&n=seqLTE3JlSrVAtw9\&q=85\&s=b6f3103b49ea1050c05b08781ee5313e)

Applications should emit structured JSON logs to stdout/stderr. The platform is responsible for collecting, enriching, storing, and serving those logs.

## The logging pipeline — stages and choices

A typical production logging pipeline has five stages. Each stage can affect cost, retention, and query performance.

| Stage | Purpose | Common options / notes |
| - | - | - |
| Collect | Read container log files or receive log lines from apps | DaemonSet collectors (Fluentd, Fluent Bit, Promtail) or per-pod sidecars |
| Enrich | Attach Kubernetes metadata and contextual fields | Add namespace, pod name, container name, labels, annotations |
| Forward | Send logs to a central store or buffer | Use output plugins to Elasticsearch, Loki, or cloud logging APIs |
| Store & Index | Persist logs and make them searchable | Elasticsearch (full-text indexing) vs. Grafana Loki (label-based indexing, cost-efficient) |
| Query & Visualize | Search, explore, alert, and build dashboards | Kibana for Elasticsearch; Grafana for Loki; integrate with traces and metrics UIs |

Practical notes:

* Storage and indexing choices drive cost and query UX: full-text search is powerful but expensive; label-indexed stores are cheaper and scale better for high-volume logs.
* Ensure retention policies align with compliance and incident response needs (e.g., 30 days, 90 days, etc.).

## Collectors in Kubernetes: DaemonSet vs Sidecar

There are two common collection patterns in Kubernetes:

* DaemonSet (recommended default)
  * One collector per node tails files such as `/var/log/containers/*.log`.
  * Pros: low overhead, simple, handles the majority of use cases.
  * Start with this pattern for most clusters.

* Sidecar (per-pod)
  * A collector container runs in the same pod as the application, useful for apps that emit complex or multiline formats and need per-app parsing.
  * Cons: more resource usage (collector runs per pod).
  * Use only for exceptions where node-level collection can't parse logs correctly.

![An infographic comparing Kubernetes log collection patterns, showing the DaemonSet and Sidecar approaches with their "How", "Pros", "Cons", and "Use" summaries. It recommends starting with a DaemonSet for most cases and adding sidecars only for apps needing custom log handling.](https://mintcdn.com/kodekloud-c4ac6d9a/seqLTE3JlSrVAtw9/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Observability-and-Operations/Logging-for-Platforms-Patterns-That-Scale/kubernetes-log-collection-daemonset-sidecar.jpg?fit=max\&auto=format\&n=seqLTE3JlSrVAtw9\&q=85\&s=adcac39d712eae323b4f5bc764edefa8)

## Log levels: signal vs noise

Choosing and enforcing the correct log levels prevents alert fatigue and keeps signal visible.

* ERROR: Failure that should be investigated and often alert on.
* WARN: Concerning events that the system recovered from — useful for trends.
* INFO: Normal operational events — production default.
* DEBUG: Verbose diagnostics — enable only for targeted investigation.

Production guidance:

* Default to `INFO`.
* Alert on `ERROR`.
* Dashboard `WARN` as a trend.
* Enable `DEBUG` only for limited scopes or temporary investigations.

![An infographic titled "Log Levels: Signal vs Noise" that lists ERROR, WARN, INFO, and DEBUG with their meanings, example events, and recommended actions. It also includes a production strategy: run at INFO, alert on ERROR, track WARN, and enable DEBUG only when investigating.](https://mintcdn.com/kodekloud-c4ac6d9a/seqLTE3JlSrVAtw9/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Observability-and-Operations/Logging-for-Platforms-Patterns-That-Scale/log-levels-signal-vs-noise.jpg?fit=max\&auto=format\&n=seqLTE3JlSrVAtw9\&q=85\&s=8d95d8929cfcd90adf46902713717ec8)

## Tracing integration — connect logs and traces

When your [OpenTelemetry](https://opentelemetry.io/) SDK is active, it can inject the current trace ID into the logging context. With the proper logging integration or middleware, logs emitted within a trace context include a `trace_id` field.

Example incident flow:

1. [Grafana](https://grafana.com/) alerts on an error-rate spike.
2. Search the central logs for `level="error"` during that window.
3. Locate an error log such as "charge failed — gateway timeout" that includes `trace_id`.
4. Click the `trace_id` (if your log UI links to traces) to open [Jaeger](https://www.jaegertracing.io/) and inspect the waterfall — you'll see exactly where the gateway span timed out.
5. You’ve moved from “something’s wrong” to a focused root-cause by following one ID across metrics, traces, and logs.

## Best practices and responsibilities

* Emit structured JSON logs to stdout/stderr from every service.
* Include contextual fields (service, environment, pod metadata, `trace_id`, user identifiers when appropriate).
* Platform teams should operate the collector, enrichment, storage, retention, and query UX.
* Start with DaemonSet collectors and add sidecars only when necessary.
* Ensure logs that may contain sensitive data are redacted before storage or handled under strict access controls.

![A presentation slide titled "Key Takeaways" with colorful numbered icons down the left. It lists four brief points about logging and observability (kubectl logs not scaling, use structured JSON, DaemonSet-based collection, and using trace IDs to link metrics/traces/logs).](https://mintcdn.com/kodekloud-c4ac6d9a/seqLTE3JlSrVAtw9/images/Prep-Course-Certified-Cloud-Native-Platform-Engineering-CNPE/Observability-and-Operations/Logging-for-Platforms-Patterns-That-Scale/key-takeaways-logging-json-daemonset-traceids.jpg?fit=max\&auto=format\&n=seqLTE3JlSrVAtw9\&q=85\&s=10ca7aa591146d56cee367a256020863)

Metrics, traces, and logs together provide a unified observability story: use structured logs, centralize collection and storage, and inject trace IDs so you can move seamlessly from alerts to traces to detailed logs.

## Links and references

* [kubectl logs command reference](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs)
* [Fluentd](https://www.fluentd.org/)
* [Fluent Bit](https://fluentbit.io/)
* [Promtail (Grafana Loki client)](https://grafana.com/docs/loki/latest/clients/promtail/)
* [Elasticsearch](https://www.elastic.co/elasticsearch/)
* [Grafana Loki](https://grafana.com/oss/loki/)
* [Kibana](https://www.elastic.co/kibana/)
* [Grafana](https://grafana.com/)
* [OpenTelemetry](https://opentelemetry.io/)
* [Jaeger Tracing](https://www.jaegertracing.io/)

> **[Watch Video](https://learn.kodekloud.com/user/courses/prep-course-certified-cloud-native-platform-engineer-cnpe/module/9bd090c8-8d99-4742-b50c-ae63e516e6b9/lesson/96beb568-bbf6-4b91-9be1-543fdff42992)**


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.