Expert · Monitoring and logging · topic 40 of 53 · 30 min
Logging: structured, safe and centralised
Explanation
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.
{"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"}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
| Level | Use it when | Example |
|---|---|---|
| DEBUG | Detail for developers; usually off in production | Cart total computed: 3 items, 1,247 rupees |
| INFO | Normal, expected events worth recording | Order A1029 placed |
| WARN | Something odd happened but the system coped | Gateway slow (2.4 s), retrying |
| ERROR | An operation failed and needs attention | Payment failed after 3 attempts |
| FATAL | The process cannot continue and will exit | Cannot 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.
| Option | Parts | Notes |
|---|---|---|
| ELK / Elastic Stack | Elasticsearch (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 |
| EFK | Elasticsearch, Fluentd or Fluent Bit, Kibana | Common on Kubernetes; Fluent Bit is a light agent per node |
| Grafana Loki | An agent such as Grafana Alloy or Fluent Bit, Loki, Grafana | Indexes only labels (app, namespace, level), not the full text, so storage is cheaper; queries use LogQL |
| Cloud services | Amazon CloudWatch Logs, Google Cloud Logging, Azure Monitor Logs | Little to run yourself; you pay per GB ingested and stored |
{app="payments", namespace="prod"} | json | level="ERROR" | reason="gateway_timeout"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.
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
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.
{"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"}Practice (0/3 done)
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).
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.
Which log line is safe to write in production?
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Alerting and on-callMonitoring and logging · same module
- Logging and monitoringBackend Development · Performance and reliability
- Logs and log sourcesCyber Security: from zero to SOC analyst · Logs, SIEM and incident response
- Files, time and structured logsGo Programming (backend and cloud) · Standard library essentials
- Monitoring with CloudWatch, CloudTrail and ConfigCloud Computing (AWS, Azure, Google Cloud) · Serverless, monitoring and cost control
- Keeping secrets safeBackend Development · Backend security
Questions people ask about this
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.
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.
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.
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 more topic in “Monitoring and logging” before its exam: Alerting and on-call.
- Module 9 exam: Monitoring and logging · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, SRE: reliability and incidents. 53 topics left in the course before the final exam.