Inside a logging service
medium 30 minA logging service carries the log lines of all programs to one place where people can search them.
Video lesson · Chapter 1 of 6
Carry structured events to the index
Theory
Read or listen first. About 2 min.
What it is
A log is a record of one event: what happened, when, and in which program. A distributed logging service collects the logs of many programs on many machines, stores them in one place, and makes them searchable.
It is a pipeline with six jobs: generate, collect, buffer, process, index and query. Each job can be done by a different program, and each can be slow or broken without stopping the others.
Why it exists
With one server you can open a file and read it. With two hundred servers, half of which existed only for an hour, nobody can do that. The machine that failed may already be gone, and its file with it.
One request often passes ten services. To understand why it failed you need the lines of all ten together, in order. That works only if they are in one place and carry the same id.
The search must also be fast while something is broken. At that moment everybody logs more than usual, so the logging service gets its hardest test exactly when people need it.
A short history
1980s
Eric Allman writes syslog. RFC 3164 names Allman as the inventor.
August 2001
RFC 3164 describes the syslog protocol that machines had long been using.
March 2009
RFC 5424 replaces it and adds structured data to a message.
February 2010
The first version of Elasticsearch is released. With Logstash and Kibana it later becomes the ELK stack.
December 2018
Grafana Labs introduces Loki, which indexes only labels and not the text of the lines.
November 2021
The current W3C Trace Context recommendation is published: one header that carries the id of a request.
Words to know
- Structured log
- A record with named fields, usually JSON.
- Agent
- A small program on each machine that reads log lines and sends them on. Also called a shipper.
- Buffer
- A queue between senders and the store that absorbs bursts and outages.
- Inverted index
- A list that says for each word which lines contain it.
- Shard
- One part of an index, on one machine.
- Trace id and span id
- The id of a whole request, and the id of one step of it.
- Ingestion delay
- The time between an event and the moment you can find it.
- Retention
- How long a kind of log is kept.
- Backpressure
- A slow receiver making the sender wait or drop.
Understand it
Start here
Captains' logbooks in the harbour office
The captains never wait for the office. They write and sail on.
| At the harbour | In the system |
|---|---|
| Captain writing | A service |
| Book | A log on one machine |
| Porter | Agent |
| Basket | Queue |
| Clerk | Processor |
| Card with words | Inverted index |
| Crate number | Trace id |
The idea
Six properties people want
A good logging service is
Central
All lines in one place, also those of machines that no longer exist.
Searchable
Find one word among billions of lines.
Fresh
A line can be found seconds after it was written.
Scalable
More machines, more lines, the same speed.
Correlated
One id joins the lines of one request.
Alerting
A pattern of errors calls a person.
Say it in one sentence: every service writes what it does, agents carry the lines to one place, an index answers questions such as "all errors of the payment service in the last hour", and one id follows a request through ten services.
Logs are one of three kinds of data. Load balancer monitoring shows how metrics, logs and traces work together, and monitoring basics explains metrics.
Requirements
What to agree on first
| Requirement | A target to start from | Why it matters |
|---|---|---|
| Writing | 100,000 lines a second on average, 300,000 at peak | Decides the number of partitions and shards |
| Freshness | Searchable within 5 seconds | Decides batch sizes |
| Search | Under 1 second for recent data | Decides what stays on fast disks |
| Loss | At least once for errors and audit lines | Decides buffering on disk |
| Search available | 99.9% | Decides replicas and zones |
| Recovery | A failed node is replaced by itself | Decides replication |
How much is it?
The whole
The pipeline
From a line to an answer
One line on its way
Who does which job
| Job | Examples |
|---|---|
| Collect | Fluentd, Fluent Bit, Filebeat, Vector |
| Buffer | Kafka, Kinesis |
| Process | Logstash, Vector, your own consumers |
| Store and index | Elasticsearch, Loki, ClickHouse |
| Search and show | Kibana, Grafana |
In the ELK stack, Logstash parses free text with patterns called grok, adds fields such as a country, and decides where a line goes. Elasticsearch stores and searches, split over shards. Kibana is the page for searching, charts and alert rules.
Write
Structured lines
2024-01-15 10:23:45 ERROR Payment failed for user 123,order 456, amount 99.99 - timeout{ "id": "01HM5Z-0001", "timestamp": "2024-01-15T10:23:45.120Z", "level": "ERROR", "service": "payment", "version": "1.4.2", "host": "pay-7", "environment": "production", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "span_id": "00f067aa0ba902b7", "message": "payment failed", "error": "timeout", "user_id": "123", "order_id": "456", "amount": 99.99}Levels
| Level | Use it for | In production |
|---|---|---|
| DEBUG | Details for one investigation | Off, or for a short time |
| INFO | Normal steps that matter | Yes, sampled if many |
| WARN | Odd but handled | Yes |
| ERROR | One operation failed | Always |
| FATAL | The process stops | Always |
Collect
Agents, push and pull
Push: the sender sends
- Arrives quickly.
- The sender decides what is sent.
- Works through firewalls that allow only outgoing traffic.
- The receiver can be flooded, so it needs backpressure.
Pull: the receiver asks
- The receiver sets the pace.
- Backpressure comes for free.
- A little slower.
- The receiver must know all senders.
Logs are nearly always pushed: Fluentd, Filebeat and direct Kafka producers all send. Pull is usual for metrics, as in Prometheus. In the middle there is pull too: consumers fetch from Kafka at their own speed. Push and pull compares both.
Four agents
| Agent | Known for | Think of |
|---|---|---|
| Fluentd | Many plugins. C and Ruby, over 60 MB of memory by its own comparison | Routing and changing on a central node |
| Fluent Bit | C, about 450 KB by the same comparison | On every container host |
| Filebeat | Light. Delivers at least once | Files to Elastic |
| Vector | Written in Rust. Logs and metrics | High volume |
Why batch? A hundred lines of 500 bytes in one message need one round trip and one set of headers, and they compress well because they look alike. The price is delay: send after 100 lines or 1 second, whichever comes first.
Filebeat writes down how far it has read. After a restart it continues there and may send some lines twice. That is at least once. Give each line an id, and let the index use it as the document id: the second copy then overwrites the first.
Buffer
The queue in the middle
The queue separates those who write from those who store. If the index is slow for an hour, lines wait and nobody loses anything. If a second team wants the same lines, it reads them from the same queue. How such a log works inside is the subject of log-based queues.
How long can the index be away?
And if the queue is away? The agent keeps lines on its own disk. A machine with 200 lines a second writes 100 KB a second, so 10 GB last 100,000 seconds, about 28 hours.
The buffer is full. What now?
Store
The inverted index
| Line | Text |
|---|---|
| 1 | Payment failed for user |
| 2 | Order failed validation |
| 3 | Payment succeeded |
| Word | Lines |
|---|---|
| failed | 1, 2 |
| succeeded | 3 |
| payment | 1, 3 |
| order | 2 |
A new line is not searchable at once. By default Elasticsearch makes new lines visible every second, for indices that were searched in the last 30 seconds. That is why it calls itself near real time.
An index costs processor time and space for every field. Loki takes another way: it indexes only a few labels per stream, such as service and environment, and reads through the compressed text at query time. Writing is cheap, and a search without a narrow label is slow.
Index all or index labels
| Full index (Elasticsearch) | Labels only (Loki) | |
|---|---|---|
| Write cost | High | Low |
| Find a rare word anywhere | Fast | Scans everything |
| Find it in one service, one hour | Fast | Fast enough |
| Danger | Too many fields | Too many label values |
Split by time: one index per day or per size. A question about the last hour then touches one index, and deleting a day means dropping an index instead of deleting lines one by one. The mechanics of search are in full-text search.
Age
Hot, warm, cold, gone
| Tier | Age, for example | Where | Questions |
|---|---|---|---|
| Hot | 0 to 2 days | Fast SSD | Most |
| Warm | 2 to 30 days | Cheaper disks, segments merged | Some |
| Cold | Over 30 days | Object storage such as S3 | Rare, slower |
An example policy
| Kind | Hot | Warm | Cold | Delete after |
|---|---|---|---|---|
| Security and audit | 7 days | 90 days | 7 years | What the law says |
| Application errors | 3 days | 30 days | 90 days | 1 year |
| Debug | 1 day | 7 days | 14 days | 30 days |
| Access | 2 days | 14 days | 30 days | 90 days |
The life of an index
Ask
Questions people ask
| Question | Filter |
|---|---|
| All errors | level:ERROR |
| Errors of payment | level:ERROR AND service:payment |
| One request | trace_id:"abc-123" |
| Last hour | @timestamp:[now-1h TO now] |
| Slow ones | response_ms:>1000 |
{ "size": 0, "query": { "term": { "level": "ERROR" } }, "aggs": { "by_service": { "terms": { "field": "service" } }, "over_time": { "date_histogram": { "field": "@timestamp", "fixed_interval": "1h" } } }}service must be a keyword field.Always start with a time range and a service. A search for a word over everything touches every shard and slows the search of the person beside you.
Counting by reading logs is expensive. If a number is needed every minute, make a metric of it when the line is processed.
Join
One request, many logs
The same trace id everywhere
The id is made once, at the entrance, and travels in the traceparent header. A service that finds no id may start a trace, but a logger that invents a new id for every line joins nothing at all.
Clocks of machines differ by some milliseconds. So the order of lines from two machines is not certain. Use the parent of each span to know which step called which.
Fail
What breaks, and what to do
| Failure | What people see | Answer |
|---|---|---|
| A release logs 20 times more | Queue grows, search is late | Limit per service, sample, alert on volume |
| The index rejects lines | Holes | Put them in a separate queue, alert |
| One field has two types | Rejected lines | A shared schema, checked in tests |
| A user field makes thousands of fields | Index slow | Put free data into one field |
| The logging service is down | Nobody sees it | Alert from outside it |
Summary
The whole topic in one minute.
A logging service is a pipeline: programs write structured lines, agents collect and batch them, a queue absorbs bursts, processors clean and enrich, an index makes them searchable, and old lines move to cheaper storage until they are deleted.
Three choices decide whether it works: every line carries a trace id, writing a line never blocks the program, and there is a plan for what to drop first. Volume decides the cost, so keep what people use.
- Generate, collect, buffer, process, index, query.
- Structured lines, a trace id in each, nothing secret.
- Writing a line never blocks the program.
- At least once plus an id per line.
- Split by time, move to cheaper tiers, delete on purpose.
- Volume is the cost: sample, limit, count what you drop.