Skip to content

Expert · Monitoring and logging · topic 40 of 53 · 30 min

Logging: structured, safe and centralised

Explanation

Logs are time-stamped records of events that tell you exactly what happened. Write them as structured JSON with a timestamp, level, message and a request or trace ID, use log levels correctly, and never log secrets or personal data such as passwords, card numbers or Aadhaar numbers. Send logs from every server to one central place (Elastic Stack, EFK, Grafana Loki or a cloud log service) and control how long you keep them.

Why logs?

A metric tells you that 3% of payments failed. A log tells you which order failed, for which reason, at which second. Logs are the detailed diary of your system. You read them when debugging, when a customer complains about a specific transaction, and during security investigations.

From plain text to structured logs

An old-style log line is free text: "Payment failed for order A1029 after 3 tries". A human can read it, but a program has to guess where the order ID is. A structured log writes the same event as fields, usually one JSON object per line. Machines can then filter and count by any field.

json
{"timestamp":"2026-10-19T20:15:02.481+05:30","level":"ERROR","service":"payments","message":"Payment failed","order_id":"A1029","attempts":3,"reason":"gateway_timeout","request_id":"req-7f3a9c","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}
One structured log line: every value has a name, so you can search for reason="gateway_timeout" across all servers.

Useful fields in every line: timestamp (ISO 8601 with the time zone), level, service name, message, and a request_id or trace_id so you can follow one request. Add business IDs like order_id when they help, but think before adding anything personal.

Log levels

LevelUse it whenExample
DEBUGDetail for developers; usually off in productionCart total computed: 3 items, 1,247 rupees
INFONormal, expected events worth recordingOrder A1029 placed
WARNSomething odd happened but the system copedGateway slow (2.4 s), retrying
ERRORAn operation failed and needs attentionPayment failed after 3 attempts
FATALThe process cannot continue and will exitCannot read database password, shutting down

Choose the level by asking: "Does someone need to act on this?" Normal traffic is INFO, not ERROR. If every 404 is logged as ERROR, real errors drown. Set the minimum level by configuration, so you can turn DEBUG on for ten minutes while investigating without a new deploy.

Never log secrets or personal data

Logs are copied to many places and read by many people: developers, support staff, vendors. Anything in a log should be treated as widely visible. Never log passwords, OTPs, API keys, tokens, full card numbers or CVVs, Aadhaar or PAN numbers, or full request bodies of login and payment calls. India's Digital Personal Data Protection Act, 2023 makes companies responsible for personal data they hold, and that includes their logs.

Defend in layers: do not put the data in the message at all; mask it in the logging library (show only the last 4 digits); and scan logs for patterns like 12-digit numbers or email addresses before they leave the server.

Centralised logging

On one server you can run tail -f. With 40 pods that come and go, a crashed pod takes its logs with it. Centralised logging means an agent on each machine collects logs and ships them to one store, where you can search everything together.

OptionPartsNotes
ELK / Elastic StackElasticsearch (store and full-text search), Logstash (process), Kibana (UI), plus Beats such as Filebeat (ship)Powerful search on any word; indexing everything needs a lot of storage and memory
EFKElasticsearch, Fluentd or Fluent Bit, KibanaCommon on Kubernetes; Fluent Bit is a light agent per node
Grafana LokiAn agent such as Grafana Alloy or Fluent Bit, Loki, GrafanaIndexes only labels (app, namespace, level), not the full text, so storage is cheaper; queries use LogQL
Cloud servicesAmazon CloudWatch Logs, Google Cloud Logging, Azure Monitor LogsLittle to run yourself; you pay per GB ingested and stored
output
{app="payments", namespace="prod"} | json | level="ERROR" | reason="gateway_timeout"
LogQL: select streams by label, parse the JSON, then keep only gateway timeouts.

Correlation IDs and OpenTelemetry

A correlation ID (request ID) is a unique ID created when a request enters your system, passed to every service in a header, and written in every log line. Searching for request_id="req-7f3a9c" then shows the whole story across services. Tracing systems do this with a trace ID, carried in the standard W3C traceparent header.

OpenTelemetry (OTel) is a vendor-neutral, open standard from the CNCF for producing traces, metrics and logs. You add its SDK to your code once; the OpenTelemetry Collector then sends the data to whichever backend you choose. Because log lines and spans share the same trace ID, you can jump from a slow trace to its logs.

Retention and cost

Logs can cost more than the servers they describe. Keep DEBUG off in production, sample very noisy INFO logs, and drop health-check logs. Set retention: for example, 15 days searchable and 1 year in cheap object storage. Regulated businesses such as banks may have to keep some logs longer, so check with your compliance team.

Careful: Common mistakes: (1) Logging passwords, OTPs or full request bodies. (2) Logging everything at ERROR, so alerts on errors become useless. (3) No request ID, so you cannot connect lines from different services. (4) Free-text logs that need fragile regex to search. (5) Keeping all logs forever "just in case" and getting a huge bill.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Logging: structured, safe and centralised · 1/8

Logging

In this lesson you will learn how to write logs that are useful, safe, and easy to search.

Prefer a video by a teacher? Find free videos on “structured logging best practices ELK Loki centralised logging tutorial” on YouTube ↗

In real life: A customer complaint at a fintech support desk

A customer of a lending app in Bengaluru says her EMI payment was deducted but the app still shows it as due. The support agent finds the payment's request ID on the receipt and searches the central log store for it. Twelve lines from four services appear in order: the payment succeeded at the gateway, the callback reached the API, but the ledger service logged an ERROR "duplicate key" and retried three times. The engineer fixes the ledger entry the same day. The logs showed only the last 4 digits of her account number, so the agent never saw her full details.

json
{"timestamp":"2026-10-19T11:04:27.120+05:30","level":"ERROR","service":"ledger","message":"Insert failed: duplicate key","request_id":"req-91c2e0","loan_id":"LN-55821","account_last4":"4417"}
Enough detail to debug, and no full account number.

Practice (0/3 done)

Task 1 · Code · Python

Write filter_logs(lines, min_level). Each item in lines is a string holding one JSON log object with "level" and "message". Levels in order are DEBUG < INFO < WARN < ERROR < FATAL. Return the list of messages whose level is at or above min_level, in the original order. Skip any line that is not valid JSON (real logs sometimes contain junk).

Task 2 · Code · Python

Write mask(message) that hides personal data before a message is logged. Replace every email address with "[EMAIL]" and every 12-digit Aadhaar-like number with "[AADHAAR]". An Aadhaar-like number is 12 digits, optionally written in groups of 4 separated by single spaces or hyphens (1234 5678 9012, 1234-5678-9012 or 123456789012). Do not change shorter numbers such as order IDs or amounts. Use the re module.

Task 3 · Question

Which log line is safe to write in production?

Quick quiz

Question 1

1.A payment retry succeeded on the second attempt. Which level fits best?

Question 2

2.What does Grafana Loki index?

Question 3

3.What is a correlation ID (request ID) for?

Question 4

4.In the ELK stack, what does Kibana do?

Question 5

5.What is OpenTelemetry?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

A payment retry succeeded on the second attempt. Which level fits best?

Answer: WARN

Something odd happened but the system coped, which is what WARN is for.

What does Grafana Loki index?

Answer: Only labels such as app, namespace and level

Loki indexes labels and stores the text compressed, which keeps storage costs down.

What is a correlation ID (request ID) for?

Answer: Finding all log lines, across services, that belong to one request

The same ID in every line lets you follow one request across many services.

In the ELK stack, what does Kibana do?

Answer: Gives a web UI to search and visualise the logs

Elasticsearch stores and searches, Logstash processes, Kibana is the UI; Beats ship the data.

What is OpenTelemetry?

Answer: A vendor-neutral open standard and toolkit for traces, metrics and logs

OpenTelemetry (CNCF) lets you instrument once and send data to any backend.

Which of these is safe to put in a log line?Related

Answer: The order id

An order id is not secret. Passwords, card numbers and OTPs must never be logged.

From Logging and monitoring

Why forward logs to a central server?Related

Answer: An attacker on a machine can delete its local logs

Central copies survive even if a host is wiped.

From Logs and log sources

Which of these should never appear in logs?Related

Answer: A user's OTP or password

Secrets in logs are a serious security leak.

From Files, time and structured logs

What is the default retention of a new CloudWatch Logs log group?Related

Answer: Never expire

Logs are kept forever unless you set a retention period, which is why forgotten log groups slowly grow the bill.

From Monitoring with CloudWatch, CloudTrail and Config

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Monitoring and logging” before its exam: Alerting and on-call.
  2. Module 9 exam: Monitoring and logging · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, SRE: reliability and incidents. 53 topics left in the course before the final exam.

← Previous: Prometheus and Grafana