Skip to content

No. 33DevOps8 min read2,095 words

Observability basics: logs, metrics and traces for web apps

Observability for production web apps: what logs, metrics and traces each answer, structured logging and OpenTelemetry for Next.js, and alerts that work.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Logs tell you what happened to one request, metrics tell you when something changed across all requests, and traces tell you where the time went inside a single request.
  2. 02Start with structured JSON logs that carry a request ID and trace ID, redact secrets at the logger, and return the request ID to the client so support can find any failure in one query.
  3. 03Watch latency, traffic, errors and saturation on your critical routes; these four signals, from Google's SRE book, catch most real outages.
  4. 04Next.js supports OpenTelemetry out of the box: an instrumentation.ts file with @vercel/otel gives you request and fetch spans, and onRequestError captures unhandled server errors.
  5. 05Alert only on symptoms users feel, give every alert an owner and a next step, and page a human only when something needs action now.
On this page ยท 10

Observability is your ability to explain what a production system is doing, and why, from the data it already emits. For a web app, that means three signals: structured logs for what happened to a specific request, metrics for when behaviour changed across all requests, and traces for where the time went inside one request. You get most of the value from a modest setup: JSON logs with request IDs, a few key metrics on critical routes, OpenTelemetry traces, and a small number of sharp alerts.

Most apps ship to production with exactly one observability tool: the feeling you get when a user emails to say something is broken. That works right up until it does not, usually at 2 a.m., usually during a sale. Good observability turns "the site feels slow" into "checkout latency jumped at 14:03 because the payments API started timing out." This is the baseline we set up on projects we build and maintain through our cloud and DevOps practice.

What observability means, without the vendor noise

There is a lot of marketing around the word, so here it is plainly. Monitoring answers questions you knew to ask in advance: is the error rate above 2 percent? Observability is being able to ask new questions, during an incident, without deploying new code to answer them. The OpenTelemetry observability primer describes it the same way, built on three signals.

SignalWhat it isQuestion it answersExample
LogsDiscrete events with contextWhat happened to this request or user?"Order 9930 failed: card declined"
MetricsNumbers aggregated over timeWhen did behaviour change, and how much?Error rate, requests per second, latency percentiles
TracesThe path of one request through your code and servicesWhere did the time go?30 ms in the handler, 2.1 s waiting on Postgres

You do not need all three on day one. You do need to know which question each one answers, because reaching for the wrong signal is how people burn an afternoon searching logs for something a single latency graph would have shown in five seconds.

Step 1: structured logs with a request ID

If you only do one thing this quarter, make your logs structured. A line like console.log("order failed", err) is invisible to every tool that could help you. JSON logs with consistent fields are queryable, filterable and groupable.

Use a real logger. In Node, pino is fast and unopinionated. This setup redacts secrets and stamps every line with the active trace ID, so logs and traces link up later.

// lib/logger.ts
import pino from "pino";
import { trace } from "@opentelemetry/api";
 
export const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
  // Redact anything that must never reach your log store.
  redact: ["req.headers.authorization", "req.headers.cookie", "*.password", "*.token"],
  base: { service: "checkout-api", env: process.env.NODE_ENV },
  // Attach the current trace and span IDs to every log line.
  mixin() {
    const span = trace.getActiveSpan();
    if (!span) return {};
    const { traceId, spanId } = span.spanContext();
    return { traceId, spanId };
  },
});
// app/api/orders/route.ts
import { randomUUID } from "node:crypto";
import { logger } from "@/lib/logger";
import { createOrder } from "@/lib/orders";
 
export async function POST(req: Request) {
  const requestId = req.headers.get("x-request-id") ?? randomUUID();
  const log = logger.child({ requestId, route: "POST /api/orders" });
  const start = performance.now();
 
  try {
    const order = await createOrder(await req.json());
    log.info({ orderId: order.id, durationMs: performance.now() - start }, "order created");
    return Response.json(order, { headers: { "x-request-id": requestId } });
  } catch (err) {
    log.error({ err, durationMs: performance.now() - start }, "order creation failed");
    return Response.json({ error: "internal_error", requestId }, { status: 500 });
  }
}

Two details matter more than they look. Returning the requestId to the client means a user can paste it into a support ticket and you can find the exact failure in one query. And redact is not optional. The fastest way to turn an observability project into a security incident is to log a full request with a session cookie in it. The OWASP Logging Cheat Sheet lists what to exclude: passwords, session identifiers, access tokens, payment card data and sensitive personal data, among others.

Write logs to stdout and let your platform ship them. Your app should not care where logs end up.

Log levels people actually stick to

Pick a discipline and hold it:

  • error: something failed and a human or a retry needs to deal with it.
  • warn: degraded but handled. A fallback kicked in, a retry succeeded.
  • info: meaningful business events. Order created, payment captured, user signed up.
  • debug: noisy detail you switch on temporarily via LOG_LEVEL.

If everything is info, nothing is. Levels exist so you can alert on error, sample info and drop debug in production without losing the plot.

Step 2: the metrics that catch real outages

Logs are great for the specific request you already know is broken. They are a poor way to notice that error rates are climbing across thousands of requests. That is what metrics are for.

Google's SRE book names four golden signals for user-facing systems, and they are the right place to start:

SignalWhat to measure in a web appWhy it matters
Latencyp50, p95 and p99 response time per critical route, split by success and errorAverages hide the slow tail your unhappiest users feel
TrafficRequests per second per routeExplains everything else: a spike in errors during a traffic spike is a capacity problem
ErrorsRate of 5xx responses and failed business actions (checkout, signup)The most direct proxy for user pain
SaturationCPU, memory, database connection pool usage, queue depthTells you how close you are to falling over

You may also see the RED method (rate, errors, duration), which is the same idea for request-driven services without saturation. Either way, a few numbers on your critical routes beat hundreds of metrics nobody reads.

Your hosting platform probably gives you traffic, latency and error rate per route for free. The metrics you have to add yourself are usually business events (failed checkouts) and saturation of shared resources, especially the database pool.

Step 3: traces with OpenTelemetry in Next.js

When a metric alert fires, you want to know why the slow requests are slow. Traces answer that. A trace breaks one request into spans: time in your handler, time in the database, time in each downstream call. OpenTelemetry is the vendor-neutral standard for producing them, and Next.js instruments itself with it out of the box.

The Next.js OpenTelemetry guide recommends @vercel/otel (installed with the @opentelemetry/sdk-logs, @opentelemetry/api-logs and @opentelemetry/instrumentation packages) and a single instrumentation.ts file in the project root:

// instrumentation.ts
import { registerOTel } from "@vercel/otel";
import type { Instrumentation } from "next";
 
export function register() {
  registerOTel({ serviceName: "checkout-api" });
}
 
// Called for every unhandled server error: renders, route handlers, actions, proxy.
export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => {
  if (process.env.NEXT_RUNTIME !== "nodejs") return;
  const { logger } = await import("./lib/logger");
  const error = err as Error & { digest?: string };
  logger.error(
    {
      err: error,
      digest: error.digest,
      path: request.path,
      method: request.method,
      routePath: context.routePath,
      routeType: context.routeType,
    },
    "unhandled request error",
  );
};

register gives you automatic spans for incoming requests and outgoing fetch calls. The onRequestError hook catches server errors that never reach your own try/catch, including errors thrown while rendering Server Components, and the digest matches the ID shown in the error boundary.

For the parts that matter most, your own business logic and database calls, add manual spans so the trace tells the real story:

// lib/orders.ts
import { trace, SpanStatusCode } from "@opentelemetry/api";
 
const tracer = trace.getTracer("orders");
 
export async function createOrder(input: OrderInput) {
  return tracer.startActiveSpan("createOrder", async (span) => {
    try {
      span.setAttribute("order.item_count", input.items.length);
      const order = await db.insertOrder(input);
      span.setAttribute("order.id", order.id);
      return order;
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: SpanStatusCode.ERROR });
      throw err;
    } finally {
      span.end();
    }
  });
}

Now when the latency alert fires, you open one slow trace and see the answer in the waterfall: two seconds in a single Postgres query that is missing an index. No guessing. And because the logger stamps every line with the traceId, you can jump from that trace straight to its log lines.

Across services, OpenTelemetry propagates context in the standard traceparent header, so a request that passes from your Next.js app to a separate API or worker stays one trace.

Step 4: watch the database, because it is usually the database

In a web app, the slow thing is the database far more often than people expect. Two cheap wins.

Turn on slow query logging, so Postgres tells you which statements are expensive before your users do. The log_min_duration_statement setting logs any statement slower than a threshold:

-- Log any statement that takes longer than 500 ms.
ALTER SYSTEM SET log_min_duration_statement = '500ms';
SELECT pg_reload_conf();

On a managed database you usually set this through the provider's parameter settings rather than ALTER SYSTEM. Pair it with the pg_stat_statements extension, which aggregates execution counts and timings per query shape, so you can see which queries consume the most total time, not just which single run was slowest.

Watch connection pool saturation. A surprising number of "the app is down" incidents are really "every connection in the pool is checked out and new requests are queuing." Expose pool usage as a metric and alert well before it is full. A pool sitting near its limit is a slow-motion outage you can fix during business hours instead of at 2 a.m. Our guide to scaling a web app when traffic spikes covers pooling and the other fixes.

Step 5: alerts that people do not mute

Observability without alerting is a dashboard nobody looks at until after the incident. The opposite failure is worse: forty alerts a day until the team mutes the channel and misses the one that mattered.

Rules that hold up:

  • Alert on symptoms users feel (error rate, latency, failed checkouts), not on every internal metric. High CPU with happy users is not an emergency.
  • Every alert needs an owner and a next step. An alert with no runbook is a notification, not an alert.
  • Page only for things that need a human now. Everything else goes to a dashboard or a daily digest.
  • Require a sustained condition. "Error rate above 2 percent for five minutes on checkout" survives a single bad request; "any 500" does not.

As you mature, the SRE workbook's guidance on alerting on SLOs is the best next step: define a target such as "99.9 percent of checkout requests succeed over 30 days" and alert on how fast you are burning through the allowed failures. It cuts noise dramatically because it ties every page to a promise you have made to users.

Release practices help here too. Shipping risky changes behind feature flags means the fix for a bad alert is often flipping a switch, not rushing a deploy, and a CI/CD pipeline with one-command rollback does the rest.

Do not forget the front end

Server-side signals miss everything that happens in the browser: JavaScript errors, slow hydration, a third-party script blocking input. Add client error reporting, and collect real-user performance data for Core Web Vitals. Our Core Web Vitals checklist covers measuring LCP, CLS and INP from real visits, which is often the only honest signal for low-traffic pages.

A sensible rollout order

When we inherit an app with no observability, this is the order we add it in:

  1. Structured JSON logs with request IDs and redaction.
  2. Error capture for unhandled server and client errors, including onRequestError.
  3. Latency, traffic, error and saturation metrics on the three to five routes that make money.
  4. OpenTelemetry traces, with manual spans around business logic and database calls.
  5. Postgres slow query logging and pg_stat_statements.
  6. Two or three symptom-based alerts with owners, then SLOs once the basics are stable.

Stop flying blind

You do not need an expensive observability platform to stop guessing. Structured logs with a request ID, the four golden signals on your critical routes, OpenTelemetry traces, database query visibility and a handful of sharp alerts will turn the next 2 a.m. incident into a ten-minute fix instead of an archaeology dig.

If you want this set up before your next launch, or someone to keep an eye on production after it, get in touch. Instrumenting and running production apps is a core part of our cloud and DevOps work.

For the error-tracking piece specifically, we compare Sentry, Datadog and six others in the best error monitoring tools in 2026.

FAQ ยท 05 questions

Frequently asked questions

What is the difference between monitoring and observability?

Monitoring checks known questions, such as whether error rate is above a threshold. Observability is the ability to answer new questions about your system from the data it already emits, without shipping new code. In practice, good monitoring is built on top of observable systems: structured logs, metrics and traces.

What are the three pillars of observability?

Logs, metrics and traces. Logs are individual events with context, metrics are numbers aggregated over time, and traces follow one request across functions and services. Each answers a different question, and the value comes from being able to jump between them using shared identifiers like a trace ID.

Do I need OpenTelemetry for a small web app?

Not on day one, but it is cheap to add and avoids lock-in. OpenTelemetry is a vendor-neutral standard, so you can instrument once and send data to whichever backend you choose. In Next.js it is a single instrumentation file, and it pays off the first time you need to know why a request was slow.

What should I never log?

Passwords, session tokens, API keys, full payment card numbers, and sensitive personal or health data. Redact these at the logger level rather than relying on every developer to remember. Logs are copied to more places and kept longer than your database, so a leaked secret in a log is hard to clean up.

How many alerts should a small team have?

As few as possible, usually a handful tied to user-facing symptoms on critical paths, such as a jump in error rate or slow checkout. If the team starts ignoring or muting alerts, there are too many. Everything that does not need immediate human action belongs on a dashboard or in a daily summary instead.

Filed underDevOpsBackend

Related service

Cloud & DevOps

Reliable deploys and infrastructure that gets out of the way.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts