0PricingLogin
Next.js 15 Fullstack (App Router + Server Actions) · Lesson

Structured Logging Across Server and Edge

Emit correlated, structured logs that survive serverless cold starts and Edge constraints.

Why Structured Logging Matters in Next.js 15

Traditional console.log outputs unstructured strings. In production Next.js 15 apps running across serverless functions and Edge runtimes, these strings are nearly useless: no correlation between requests, no machine-parseable fields, and cold starts discard buffered output before it flushes.

Structured logging solves this by emitting JSON objects with consistent fields on every log line:

  • requestId — ties every log to one HTTP request
  • timestamp — ISO-8601, always UTC
  • levelinfo / warn / error
  • service — which route or function emitted the log
  • message — human-readable summary
  • context — arbitrary structured payload

Observability platforms (Datadog, Axiom, Grafana Loki) ingest these fields automatically, letting you filter and correlate across thousands of concurrent requests in seconds.

The Core Logger Interface

Before integrating with any runtime, define a minimal, portable logger interface. This keeps your business logic decoupled from the concrete logging implementation and makes testing trivial.

Create lib/logger/types.ts with the shape every logger must satisfy:

// lib/logger/types.ts

export type LogLevel = 'debug' | 'info' | 'warn' | 'error';

export interface LogContext {
  requestId?: string;
  userId?: string;
  route?: string;
  durationMs?: number;
  [key: string]: unknown;
}

export interface Logger {
  debug(message: string, context?: LogContext): void;
  info(message: string, context?: LogContext): void;
  warn(message: string, context?: LogContext): void;
  error(message: string, context?: LogContext & { err?: unknown }): void;
}

export interface LogEntry {
  timestamp: string;
  level: LogLevel;
  service: string;
  message: string;
  context: LogContext;
}

All lessons in this course

  1. OpenTelemetry Tracing with instrumentation.ts
  2. Granular error.tsx and global-error Boundaries
  3. Structured Logging Across Server and Edge
  4. Capturing Server Action Failures and Telemetry
← Back to Next.js 15 Fullstack (App Router + Server Actions)