# Metrics, logs and traces

The three signals every system gives off, the question each one answers, the four golden signals to watch first, and how to read all of them on your own machine.

Course: [Monitoring](https://devops.rajeev.pro/courses/monitoring), lesson 1. About 20 minutes, intermediate. Source: https://devops.rajeev.pro/courses/monitoring/01-metrics-logs-traces

## What you will learn

- Explain the difference between monitoring and observability
- Say what metrics, logs and traces are, and which question each one answers
- Pick the right signal to start with for a real incident
- Name the four golden signals and measure two of them yourself

Every running system gives off three kinds of data: numbers, records of events and, if you add
it, the path of each request through your services. This lesson explains each one, the four
signals to watch first, and how to read them on your own machine before installing any tool. The
rest of the course builds the full stack on top of it.

## Monitoring and observability

**Monitoring** watches for problems you already know about: "alert me if the disk passes 90%"
or "if the error rate goes above 1%". **Observability** is being able to answer questions you
didn't plan for, like "why are only users on the Android app in Pune seeing timeouts since
14:02?", without shipping new code to find out.

Both are built on the same three kinds of data, often called the three signals. Each one is
good at a different question.

> **Figure.** The three signals. Metrics are numbers over time and answer whether something is wrong. Logs are records of individual events and answer what happened. Traces follow one request across services and answer where it went wrong. Below them, the four golden signals: latency, traffic, errors and saturation.
>
> Metrics tell you that something is wrong, traces tell you where, logs tell you why.

## Metrics

A **metric** is a number measured over time, with labels that say what it describes:

```text
# HELP http_requests_total Total HTTP requests handled.
# TYPE http_requests_total counter
http_requests_total{method="GET",code="200"} 1027
http_requests_total{method="GET",code="500"} 3
```

That's the text format Prometheus reads, and you'll write queries against it in the next
lesson. The main types:

| Type      | Behaves like                     | Example                                  |
| --------- | -------------------------------- | ---------------------------------------- |
| Counter   | Only goes up (resets on restart) | Requests served, errors, bytes sent      |
| Gauge     | Goes up and down                 | Memory in use, queue length, temperature |
| Histogram | Counts values into buckets       | Request duration, response size          |

Metrics are small and cheap, so you can keep months of them, graph them and alert on them.
What they can't do is tell you about one particular request.

## Logs

A **log** is a record of one event, written by the app or the system when it happens. Plain
text logs are easy to read by eye; **structured** logs (one JSON object per line) are easy for
machines to search and filter:

```json
{"time":"2026-03-14T14:02:11Z","level":"error","service":"checkout","msg":"payment declined","order":"A-1042","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}
```

Logs carry the detail metrics leave out: the error message, the order, the user. The cost is
volume: a busy service writes gigabytes a day, so logs are usually kept for days or weeks, not
months.

## Traces

A **trace** follows **one request** as it moves through your services. Each step is a
**span** with a start time and a duration, and every span carries the same **trace ID**:

```text
trace 4bf92f35…   checkout request                       1,840 ms
├─ api-gateway                                              12 ms
├─ cart-service                                             35 ms
├─ payment-service                                       1,742 ms   ← here
│  └─ POST bank-api/charge                               1,701 ms
└─ email-service (async)                                    22 ms
```

One look shows that the bank call is the slow part. Traces need the services to pass the trace
ID along with each call (usually in a `traceparent` HTTP header), which is what OpenTelemetry
sets up for you in the _Tracing_ stage.

### Which signal answers which question

| Question                                       | Start with |
| ---------------------------------------------- | ---------- |
| Is something wrong right now? Since when?      | Metrics    |
| Which service or call is slow or failing?      | Traces     |
| What exactly happened to this request or user? | Logs       |

Notice the `trace_id` in the log line above. Put the same ID in logs and traces and you can
jump from a slow trace straight to its logs. That link is what turns three separate tools into
observability.

## The four golden signals

Google's SRE book says that if you can only measure four things about a user-facing system,
measure these:

| Signal     | Asks                       | Example                               |
| ---------- | -------------------------- | ------------------------------------- |
| Latency    | How long do requests take? | p95 checkout time is 480 ms           |
| Traffic    | How much demand is there?  | 1,200 requests per second             |
| Errors     | How many requests fail?    | 0.4% of requests return a 5xx         |
| Saturation | How full is the system?    | Disk 92% full, database pool 48 of 50 |

Track latency for successful and failed requests separately: a fast error page can make
average latency look better while users are having a terrible time.

> **Averages hide pain.** If 99 requests take 100 ms and one takes 10 seconds, the average is about 200 ms and looks fine. Use percentiles: **p95** or **p99** is the time that 95% or 99% of requests finish within, and that's where unhappy users show up.

## Read the signals on your own machine

You don't need a monitoring stack to start. Every Linux machine already exposes metrics and
logs:

```sh
$ uptime                         # load average over 1, 5 and 15 minutes
 14:05:31 up 12 days,  3:41,  1 user,  load average: 0.42, 0.37, 0.30
$ free -m                        # memory, in MB: look at "available", not "free"
$ df -h                          # disk use per filesystem: saturation, at a glance
$ journalctl -p err -b -n 20     # logs: the last 20 error-level entries since boot
$ curl -o /dev/null -s -w "%{http_code} %{time_total}\n" https://example.com
200 0.254813                     # errors and latency for one request, in seconds
```

A load average higher than your number of CPU cores (`nproc`) means work is queueing: that's
saturation too.

> **Never log secrets.** Passwords, tokens, card numbers and full personal details must never reach a log. Logs get copied to many systems and kept for weeks, and many more people can read them than your database.

> **In production.** Alert on what users feel (latency and errors), not on every CPU spike. A page at 3 a.m. should always mean "users are affected and a human needs to act". Everything else is a dashboard or a ticket.

## Mission: Measure the golden signals of a website

Before adding any tools, get a baseline for a site you depend on. Send it 10 requests, record the status code and time for each, then report how many failed and how slow the slowest one was.

- You need: https://example.com (or any site you use)
- You'll have: ~/golden.txt

```sh
$ for i in $(seq 1 10); do curl -o /dev/null -s -w "%{http_code} %{time_total}\n" https://example.com; done > ~/golden.txt
$ cat ~/golden.txt
200 0.254813
200 0.198342
...
$ grep -vc '^200 ' ~/golden.txt            # errors: lines that aren't a 200
0
$ sort -k2 -n ~/golden.txt | tail -n 1     # latency: the slowest request
200 0.412907
```

Ten requests is the traffic, the non-200 count is the error rate, and the slowest time is a
rough worst-case latency. That's three of the four golden signals from one loop. Saturation
needs a view from inside the server, which is what Prometheus and node_exporter give you next.

## Try it

- Run `uptime` and `cat /proc/loadavg`, and say what the three load numbers mean.
- Run `free -m` and `df -h`, and note the fullest disk and how much memory is available.
- Show the last 20 error-level log lines from this boot with `journalctl -p err -b -n 20`.
- Use `curl -w` to print the status code and total time for a request to a website you use.
- Do the mini mission and work out the error count and the slowest request from `~/golden.txt`.

## Quiz

1. Users say checkout got slow, and checkout calls five services. Which signal tells you fastest which service is slow?
   - Metrics
   - Logs
   - **Traces** (answer)
   Why: A trace follows one request through every service and times each step, so the slow hop stands out. Metrics tell you that it's slow; the trace tells you where.

2. You want a graph of HTTP 500 errors per minute over the last week. Which signal fits?
   - **Metrics** (answer)
   - Logs
   - Traces
   Why: Metrics are numbers over time, cheap to store for long periods and built for graphs and alerts.

3. The error rate jumped at 14:02. You need the exact error message and the user ID involved. Where do you look?
   - Metrics
   - **Logs** (answer)
   - Traces
   Why: Logs hold the detail of individual events. A metric shows the jump; the logs from 14:02 say what actually failed.

4. Which of these is saturation, one of the four golden signals?
   - The number of requests per second
   - **How full a resource is, like a disk at 92% or a queue that keeps growing** (answer)
   - The share of requests that fail
   Why: Saturation is how close a system is to its limit. Requests per second is traffic, and failed requests are errors.

## Resources

- [Monitoring distributed systems (the four golden signals)](https://sre.google/sre-book/monitoring-distributed-systems/) (Google SRE book)
- [Observability primer](https://opentelemetry.io/docs/concepts/observability-primer/) (OpenTelemetry)
- [Prometheus metric types](https://prometheus.io/docs/concepts/metric_types/) (Prometheus)
- [Prometheus exposition formats](https://prometheus.io/docs/instrumenting/exposition_formats/) (Prometheus)
- [Practical monitoring advice](https://sre.google/workbook/monitoring/) (Google SRE workbook)
- [journalctl(1): reading the systemd journal](https://manpages.ubuntu.com/manpages/noble/man1/journalctl.1.html) (Ubuntu manpages)
- [curl --write-out variables](https://everything.curl.dev/usingcurl/verbose/writeout.html) (Everything curl)
