LESSON 4

Logs, Metrics, and Traces

Use the three core signals well: structured logging with levels and context, metric types and the RED, USE, and golden signals methods, distributed tracing and sampling, and investigating a problem across all three.

Introduction

Each of the three signals answers a different kind of question. Metrics tell you how much and how fast across everything. Logs tell you what happened in detail. Traces tell you where the time and failures were in one request’s journey. Teams that rely on only one signal investigate slowly: they grep logs for patterns a metric would show in seconds, or stare at graphs for causes only a trace would reveal.

This lesson shows how to design and use each signal in SignalDesk, and how to move between them during an investigation.

Learning Objectives

  • Write structured logs with consistent fields, levels, and context.
  • Choose appropriate metric types and apply the RED, USE, and golden signals methods.
  • Understand traces, spans, and sampling, and instrument a journey.
  • Follow an investigation from metric to trace to log.
  • Avoid common mistakes in each signal.
  • Use AI to review telemetry design and to summarize logs safely.

1. Logs

Structured logging

A log line written for humans is hard for machines to search. Write structured logs: each event is a record with named fields, typically in JSON.

1
2
3
4
5
6
7
8
9
Unstructured:
  2026-12-04 14:05:12 ERROR import failed for job 8841 timeout

Structured:
  {"time":"2026-12-04T14:05:12Z","level":"error","service":"worker",
   "version":"0.1.3","env":"prod","event":"import_failed",
   "job_id":"8841","tenant_id":"t_5f2a","stage":"summarize",
   "error_category":"provider_timeout","duration_ms":30012,
   "attempt":2,"trace_id":"c4a1...","message":"provider call timed out"}

The structured form can be filtered by tenant, counted by error category, and joined to the trace.

What to log

  • Events with meaning, not step-by-step chatter: request completed, job started, job failed, limit reached, configuration loaded, feature flag changed.
  • Outcomes and reasons, with a stable error category and a human-readable message.
  • Context: trace ID, job ID, tenant ID (opaque), version, and the attempt number for retries.
  • Security and audit events in a separate, protected stream: sign-ins, failures, permission changes, exports, administrative actions.
  • Key decisions, such as “rate limit applied” or “fell back to degraded mode,” which explain behavior later.

Levels

Level Use In production
Error An operation failed and someone may need to act Always on; each error should be actionable or counted
Warn Something unexpected happened but the operation continued On
Info Significant normal events On, at a modest volume
Debug Detailed diagnostic data Off by default; switchable per service for a limited time

Avoid logging an error for expected conditions, such as invalid user input; that creates noise and hides real errors.

Common mistakes

  • Logging sensitive data (secrets, personal data, customer content, model prompts).
  • Logging inside tight loops, producing floods.
  • Logging the same error at every layer as it propagates, tripling the volume. Log once, where it is handled, with context.
  • Free-text messages that vary and cannot be grouped.
  • Missing correlation identifiers.
  • Relying on logs to compute metrics at scale. Emit metrics directly; logs are for detail.
  • Local log files on instances that disappear. Ship logs to a central store.

2. Metrics

Metrics are numbers sampled or counted over time. They are cheap, fast to query, and ideal for dashboards, alerts, and SLOs.

Types

Type Meaning Example
Counter A value that only increases (reset on restart) Requests served, jobs failed
Gauge A value that goes up and down Queue depth, active connections, memory in use
Histogram A distribution of values in buckets Request duration, job duration, payload size

Use a histogram for anything where tail behavior matters (latency); do not record only an average. From a histogram you can compute percentiles such as the 50th, 95th, and 99th, and compare them against the SLO.

Labels and cardinality

Labels (also called dimensions or tags) let you slice a metric: route, status class, version, tenant tier. Keep them bounded. Good: route template (/api/imports/{id}), status class (2xx, 4xx, 5xx), outcome, version. Bad: user ID, raw URL, error message text. Unbounded labels explode storage and slow queries.

Which metrics? Three methods

Do not invent metrics at random. Use established frameworks.

The four golden signals, for any user-facing service:

Signal Question
Latency How long do requests take? (Separate successful from failed requests.)
Traffic How much demand is there?
Errors What share of requests fail, explicitly or implicitly (for example, a 200 response with wrong content)?
Saturation How full is the service? Which resource is closest to its limit?

The RED method, for request-driven services such as the API: Rate, Errors, Duration.

The USE method, for resources such as CPU, memory, disks, connection pools, and queues: Utilization, Saturation, Errors.

For SignalDesk:

Component Metrics
API Request rate, error rate by route and status class, duration histogram by route
Worker Jobs started, completed, and failed by category; stage duration histograms; jobs in progress; retries
Queue Depth, age of the oldest message, enqueue and dequeue rates (age of the oldest message is often a better signal than depth)
Database Connections used, query latency, slow queries, replication lag, storage used
Model provider Calls, errors by category, latency histogram, tokens used, cost, rate-limit responses
Business Imports per day, summaries generated, active tenants
Host or container CPU, memory, restarts, disk

The SLO indicators from lesson 2 are computed from these: good events and valid events counted as metrics.

3. Traces

A trace records the path of a single request through the system. It is made of spans: each span is one unit of work, with a start time, duration, status, and attributes, and a parent span. Together they form a tree showing where the time went.

1
2
3
4
5
6
7
8
9
10
11
POST /api/imports  (total 412 ms)
 |- authenticate                      (18 ms)
 |- validate file                     (35 ms)
 |- store file                        (210 ms)
 |- insert job record (database)      (22 ms)
 '- enqueue job (queue)               (9 ms)
        ..... later, linked by context .....
 import job (worker, total 4m 20s)
 |- parse file                        (12 s)
 |- insert rows (database)            (48 s)
 '- summarize (model provider)        (3m 52s)   <-- the long part

A trace answers “why was this one slow?” in seconds. For asynchronous work, propagate context through the queue message so that the worker’s span is linked to the original request.

Instrumenting

  • Instrument the entry points (HTTP handlers, queue consumers) and the exit points (database calls, outgoing HTTP, queue publishes). Automatic instrumentation handles many of these.
  • Add custom spans around important business stages.
  • Add attributes that help diagnosis: tenant ID, job ID, file size, row count, provider model name, retry number. Avoid sensitive content.
  • Record errors on the span, with the category and a short message.

Sampling

Storing every trace is often too expensive. Common strategies:

  • Head-based sampling: decide at the start of a request, by percentage. Simple and cheap, but may discard the interesting traces.
  • Tail-based sampling: decide after the request ends, keeping all traces with errors or high latency and a small share of the rest. Better for diagnosis, more complex to operate.

Whatever the approach, ensure that errors and slow requests are kept, and that sampling decisions are consistent across services for one trace.

4. Using the Signals Together

A typical investigation follows a path from broad to narrow:

  1. Alert or symptom. The import SLO is burning fast (metric).
  2. Scope it with metrics. Which route or stage? Which version? Which tenants? Since when? Compare to a deployment marker on the graph.
  3. Find where in the path with traces. Pick slow or failed example traces. The summarize span is slow.
  4. Find why with logs. Filter logs by the trace IDs or by error_category=provider_timeout and tenant_id. Messages show rate-limit responses from the provider.
  5. Confirm with metrics. The provider’s rate-limit counter jumped at the same time as the problem began.
  6. Form a hypothesis, test it, and act (lesson 8).

Move between signals through shared identifiers and attributes: trace ID, version, tenant, job. If a hop in this path is impossible (logs without trace IDs, metrics without version), you have found an instrumentation gap to fix.

5. Common Failure Modes of Telemetry Itself

The telemetry system is a production system, too. Watch for:

  • Silent gaps: a service stops emitting and nothing alerts, because absence of data looks like absence of problems. Alert on missing data for critical signals.
  • Clock differences between hosts that distort ordering. Synchronize clocks and record timestamps in a standard time zone format.
  • Dropped telemetry under load, exactly when you need it. Know the behavior of your agents and collectors under pressure.
  • Telemetry outages that coincide with incidents because they share infrastructure with the service. Where practical, keep monitoring independent of what it monitors.
  • Changed names or labels that silently break dashboards and alerts.
  • Lost context across queues and retries.

Test the telemetry in the same way you test features: deliberately break something in staging and verify that you can see it and find the cause.

6. Using AI With Logs, Metrics, and Traces

AI is strong at reading large volumes of text. Used well, it shortens the path from raw data to a hypothesis.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Act as a site reliability engineer helping to analyze telemetry.

Inputs (redacted: no secrets, no personal data, no customer content):
- The symptom and when it started: [describe]
- Recent deployments and configuration changes: [paste]
- A sample of structured log lines for the affected period: [paste]
- Metric summaries (rate, errors, latency percentiles, queue age)
  before and during the problem: [paste]
- Two example trace summaries, one normal and one affected: [paste]

Tasks:
1. Summarize the pattern in the logs: groups of events, counts,
   and anything that changed.
2. Compare the normal and affected traces and say where they
   differ.
3. List up to five hypotheses ranked by how well they fit the data,
   citing the specific evidence for and against each.
4. For each hypothesis, state a safe, read-only check that would
   confirm or reject it.
5. State what data is missing that would help.

Use only the data provided. Do not state a cause as fact. Do not
suggest changes to production in this step.

Practical rules:

  • Sample, then ask, rather than pasting everything; summarize by grouping first.
  • Check the AI’s counts and claims against the source data. Models miscount and misread timestamps.
  • Ask it to cite lines. An explanation that cannot point to evidence is a guess.
  • Use AI to write queries for your logging or metrics tool, then read and test them on a small range before relying on the result.
  • Use it to design telemetry: “what fields would you want in the log event for a failed import?” is a good prompt.

7. Practical Exercise

For SignalDesk (or your project):

  1. Define the structured log schema: mandatory fields, levels, error categories, and redaction rules. Convert one service’s logs to it.
  2. Define the metrics for the API, worker, queue, database, and model provider using the golden signals, RED, and USE; check labels for bounded cardinality.
  3. Implement metrics for the SLIs from lesson 2 (good and valid event counts).
  4. Instrument the import journey with traces across the API, queue, worker, and provider, with context propagated through the queue.
  5. Set a trace sampling rule that keeps errors and slow requests.
  6. In staging, cause a provider slowdown (stub the provider with delays), and follow an investigation from metric to trace to log, noting any dead ends.
  7. Add an alert for missing data on one critical signal.
  8. Run the AI telemetry analysis prompt on redacted data from your exercise, and check its claims against the raw data.

Verification

You are ready to continue when:

  • Logs are structured, centrally collected, free of sensitive data, and carry trace and job identifiers.
  • Metrics use appropriate types, bounded labels, and include the SLI inputs.
  • A request can be traced from the browser or API through the queue to the worker and provider.
  • You can follow a staged failure from metric to trace to log without guesswork.
  • Missing data on critical signals is detected.
  • Any AI analysis was checked against source data.

Key Takeaways

  • Metrics tell you how much and how fast, logs tell you what happened, and traces tell you where.
  • Structured, contextual, redacted logs are searchable and safe; metrics need bounded labels and the right types.
  • Use golden signals, RED, and USE to decide what to measure.
  • Traces must propagate context across queues, and sampling must keep the interesting ones.
  • AI helps summarize and hypothesize; check counts and claims against the raw data.

What’s Next?

Telemetry becomes valuable when it drives dashboards that people read and alerts that people trust. The next lesson covers performance monitoring: baselines, capacity, dashboards, and designing alerts that wake people only when it matters.