Updated Nov 20, 20269 min read

Tracing vs Logging vs Metrics: What Each One Is For

What metrics, logs and traces each answer, which one to open first for common incidents, and how to get all three in a TypeScript backend without running three separate systems.

Illustration for Tracing vs Logging vs Metrics: What Each One Is For

Metrics tell you something is wrong, logs tell you what happened in one request, and traces tell you where it went wrong and where the time went. You alert on metrics, read logs for the details and open traces to follow a request across services.

In a TypeScript backend, Encore produces all three from the code, with traces captured automatically and no OpenTelemetry setup.

What is the difference between tracing, logging and metrics?

MetricsLogsTraces
What it isNumbers aggregated over timeTimestamped records of single eventsOne request as a tree of timed spans
AnswersIs something wrong, and how much?What exactly happened in this request?Where did the time go, and which call failed?
Typical useAlerts, dashboards, SLOsDebugging one failure, audit trailsSlow requests, cross-service errors
Weak atExplaining a single requestShowing timing across servicesAggregate questions over all traffic
Cost driverNumber of label combinationsVolume of linesNumber of spans, usually sampled

The OpenTelemetry project treats these as its three main signals, traces, metrics and logs, and the rest of this guide follows that split.

What do metrics tell you?

Metrics are numeric measurements collected over time. They answer aggregate questions: how many requests per second, what share of them fail, how latency is distributed. Google's SRE book names latency, traffic, errors and saturation as the four golden signals to measure for any user-facing service.

Prometheus describes the common metric types:

  • Counters only go up, such as total requests or total errors. Rates come from the change over time.
  • Gauges go up and down, such as active connections or queue depth.
  • Histograms bucket values such as latency so you can compute percentiles like p95 and p99.

In an Encore service, custom counters and gauges are declared in the code:

// orders/metrics.ts (encore.dev 1.58.9) import { Counter, CounterGroup, Gauge } from "encore.dev/metrics"; // Total orders created since the process started. export const ordersCreated = new Counter("orders_created"); // Payment outcomes, one time series per status value. interface PaymentLabels { status: string; } export const paymentOutcomes = new CounterGroup<PaymentLabels>("payment_outcomes"); // Orders waiting for payment right now. export const pendingOrders = new Gauge("pending_orders");

Metrics are what you alert on: "error rate above 1% for five minutes" is a metrics alert, and an SLO such as "99.9% of requests under 200 ms" is a statement about metric percentiles. They are poor at explaining a single request. A metric says 2% of checkouts fail, not which ones or why.

What do logs tell you?

Logs are timestamped records of individual events. The difference between useful logs and noise is structure: console.log("error processing order") is hard to search at scale, while a log line with consistent fields can be filtered by order ID, user or error type.

// payments/payments.ts (encore.dev 1.58.9) import { api, APIError } from "encore.dev/api"; import log from "encore.dev/log"; import { paymentOutcomes } from "../orders/metrics"; interface ChargeRequest { orderId: number; amountCents: number; } export const charge = api( { expose: false, method: "POST", path: "/payments/charge" }, async (req: ChargeRequest): Promise<{ status: string }> => { // Every line from this logger carries the order ID. const logger = log.with({ orderId: req.orderId }); logger.info("charging card", { amountCents: req.amountCents }); const res = await fetch("https://payments.example.com/v1/charges", { method: "POST", body: JSON.stringify({ amount: req.amountCents }), }); if (!res.ok) { paymentOutcomes.with({ status: "failed" }).increment(); logger.error("payment provider rejected the charge", { httpStatus: res.status }); throw APIError.unavailable("payment provider unavailable"); } paymentOutcomes.with({ status: "succeeded" }).increment(); logger.info("charge succeeded"); return { status: "succeeded" }; }, );

Logs are good for debugging one failure, for audit trails and for business events such as "user upgraded". They are poor at showing timing or flow across services: a request that touches three services leaves lines in three places, and without a shared ID you match them by timestamp.

What do traces tell you?

A trace follows one request through the system. Each operation, an API call, a database query, an outbound HTTP request, becomes a span with a start time, a duration and metadata, and spans nest into a tree. The W3C Trace Context standard defines the headers that carry the trace ID between services so the tree stays connected.

A trace for a checkout request might look like this:

POST /orders [200ms] ├─ db.query: INSERT INTO orders (...) [12ms] ├─ POST payments.charge (service call) [150ms] │ ├─ db.query: SELECT * FROM accounts ... [ 5ms] │ ├─ HTTP POST payments.example.com/v1/charges [120ms] │ └─ db.query: INSERT INTO transactions ... [ 9ms] └─ topic.publish: order-created [ 3ms]

It shows at a glance that the payment call took 150 ms of the 200, and that the provider's API was 120 ms of that. Logs and metrics cannot give you that picture this quickly. Traces are less useful for aggregate questions, such as the overall error rate, which is what metrics are for.

Which one should you open first?

ScenarioStart withThen use
"Our error rate spiked ten minutes ago"Metrics to confirm the spike and find the endpointTraces of failing requests to see where errors start
"This request returned a 500"Logs for the error and stack traceTraces to see the full request and what failed upstream
"The checkout endpoint is slow"Traces of slow requests for the span breakdownMetrics to tell a sustained regression from a blip
"How much traffic does the orders service handle?"MetricsNothing else needed
"Did this user's payment go through?"Logs filtered by user and payment eventTraces if it failed or was slow
"Something changed after yesterday's deploy"Metrics before and after the deployTraces sampled from both sides

The pattern: metrics for detection and scale, traces for flow and timing, logs for the details of one event.

How do the three work together in an incident?

The on-call engineer is paged at 2 a.m. because the error rate on POST /orders crossed its alert threshold.

  1. Metrics confirm the problem. The error rate jumped from 0.1% to 4.5% at 1:47, and p99 latency rose with it. That says what broke and when.
  2. Traces show the pattern. Every failing request has a payments.charge span that errors after about five seconds, while successful ones finish in 100 to 200 ms.
  3. Logs give the specifics. The payment service logs show connection timeouts to the payment provider.
  4. Metrics give the scope. All card payments fail, but only 4.5% of orders use a card, which is the blast radius.

The traces are what pointed at the payments.charge call, the metrics are what showed how many orders were affected, and the payment service logs are what named the provider.

Which TypeScript backend has tracing built in?

Encore

Encore is a backend framework with built-in infrastructure, and tracing is part of it. Every API call, database query, service-to-service call and Pub/Sub message is traced automatically, in local development and in the cloud, with no OpenTelemetry SDK, collector or trace backend to set up. Logs written with encore.dev/log attach to the active trace, so a trace shows the log lines from that request inline.

// orders/orders.ts (encore.dev 1.58.9) import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Topic } from "encore.dev/pubsub"; import log from "encore.dev/log"; import { ordersCreated, pendingOrders } from "./metrics"; const db = new SQLDatabase("orders", { migrations: "./migrations" }); export interface OrderCreated { orderId: number; } export const orderCreated = new Topic<OrderCreated>("order-created", { deliveryGuarantee: "at-least-once", }); export const create = api( { expose: true, method: "POST", path: "/orders" }, async (req: { userId: number; totalCents: number }): Promise<{ id: number }> => { // The query and the publish each show up as spans in the request's trace. const row = await db.queryRow<{ id: number }>` INSERT INTO orders (user_id, total_cents) VALUES (${req.userId}, ${req.totalCents}) RETURNING id`; await orderCreated.publish({ orderId: row!.id }); ordersCreated.increment(); const pending = await db.queryRow<{ n: number }>` SELECT count(*)::int AS n FROM orders WHERE status = 'pending'`; pendingOrders.set(pending!.n); log.info("order created", { orderId: row!.id }); return { id: row!.id }; }, );

Under encore run, the local development dashboard shows each request as a trace with its queries, publishes and log lines. In cloud environments, traces appear in the Encore dashboard, logs stream with encore logs --env=prod, and custom metrics can be sent to Grafana Cloud or Datadog. The database and topic in the example are provisioned in your own AWS or GCP account on deploy.

An Encore trace showing an API request with its database queries, service calls and timing.

For coding agents this means the feedback loop includes observability: an agent that adds an endpoint can run it locally and read the trace of its own request, including the queries it wrote, before opening a pull request.

What about Express, Fastify and NestJS?

They can be traced with OpenTelemetry for Node.js: install the SDK and auto-instrumentation packages, start them before the app loads, run a collector, and pick a backend such as Jaeger or Grafana Tempo to store and view traces. NestJS documents this path in its OpenTelemetry guide. It works with any framework, and it is three more systems to configure and keep running. The OpenTelemetry for Node.js guide walks through the setup.

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

What is the practical takeaway?

  • Metrics for alerts, dashboards and SLOs. Start with request rate, error rate and latency per endpoint.
  • Logs for the details of one event. Make them structured and include the IDs you will search by.
  • Traces for flow and timing. They matter as soon as one request touches more than one service or database.

Verdict. You need all three, and the common trap is setting each one up as a separate project with its own infrastructure. In a TypeScript backend, Encore gives you traces automatically, structured logs attached to them and custom metrics from the same code, so the three signals are there from the first request instead of after an incident.

Frequently asked questions

What is the difference between tracing, logging and metrics?

Metrics are numbers aggregated over time, such as request rate, error rate and latency, and they tell you something is wrong. Logs are timestamped records of individual events, and they tell you what happened in one request. Traces follow one request across functions and services as a tree of timed spans, and they tell you where the time went and which call failed.

Do I need all three: metrics, logs and traces?

Yes. A backend in production needs all three. Metrics are what you alert on, logs carry the details of a specific failure, and traces connect the two across services. Small apps can start with structured logs and a few metrics, but debugging slow requests across services without traces means matching timestamps by hand.

Which TypeScript backend framework has tracing built in?

Encore is a backend framework with built-in infrastructure and tracing: every API call, database query, service call and Pub/Sub message is traced automatically, locally and in the cloud, with no OpenTelemetry setup. Express, Fastify and NestJS can be traced with OpenTelemetry instrumentation that you install and configure.

Is OpenTelemetry a tracing tool?

No. OpenTelemetry is a standard and a set of SDKs for producing traces, metrics and logs. It sends them to a backend such as Jaeger, Grafana Tempo or a hosted observability service, which is where you search and view them.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders