Skip to content

Repository files navigation

widelogger

Structured wide event logging for Node.js.

Accumulate context throughout a request lifecycle, then flush it as a single rich event — inspired by loggingsucks.com. Built on Pino and AsyncLocalStorage for zero-leak context isolation across concurrent requests.

Installation   ·   Usage   ·   API   ·   Contribute

Installation

To install widelogger, simply use your favourite Node.js package manager.

bun add widelogger
pnpm add widelogger
yarn add widelogger
npm install widelogger

Usage

Creating a Logger

import { widelogger } from "widelogger";

const { context, destroy } = widelogger({
  service: "checkout-api",
  defaultEventName: "http_request",
  version: "1.0.0",
  commitHash: process.env.COMMIT_SHA,
});

widelogger() returns a context function to wrap request lifecycles and a destroy function for graceful shutdown. To log fields, import widelog directly from the package — it works anywhere inside a context() call thanks to AsyncLocalStorage.

import { widelog } from "widelogger";

widelog.set("user.id", userId);

Express

Create a logger instance once, use middleware to wrap requests in a context, and accumulate fields from anywhere in your codebase by importing widelog directly.

// src/logger.ts
import { widelogger } from "widelogger";

export const { context, destroy } = widelogger({
  service: "checkout-api",
  defaultEventName: "http_request",
});
// src/middleware/logging.ts
import { widelog } from "widelogger";
import { context } from "../logger";

export const logging = (request, response, next) => {
  context(
    () =>
      new Promise((resolve) => {
        widelog.set("method", request.method);
        widelog.set("path", request.path);
        widelog.time.start("duration_ms");

        response.on("finish", () => {
          widelog.set("status_code", response.statusCode);
          widelog.time.stop("duration_ms");
          widelog.flush();
          resolve();
        });

        next();
      }),
  );
};
// src/routes/checkout.ts
import { widelog } from "widelogger";

export const checkout = async (request, response) => {
  const { userId } = request.body;

  widelog.setFields({ user: { id: userId, plan: "premium" } });

  const order = await widelog.time.measure("db_ms", () =>
    processOrder(userId),
  );

  widelog.set("order.total_cents", order.totalCents);
  widelog.count("order.items", order.itemCount);

  response.json({ orderId: order.id });
};

The handler doesn't need to know about context setup or flushing — it just imports widelog from the package and adds fields. AsyncLocalStorage ensures concurrent requests never leak into each other.

Bun

The same pattern works with Bun's built-in server.

// src/logger.ts
import { widelogger } from "widelogger";

export const { context, destroy } = widelogger({
  service: "checkout-api",
  defaultEventName: "http_request",
});
// src/routes/checkout.ts
import { widelog } from "widelogger";

export const checkout = async (request: Request) => {
  const { userId } = await request.json();

  widelog.setFields({ user: { id: userId, plan: "premium" } });

  const order = await widelog.time.measure("db_ms", () =>
    processOrder(userId),
  );

  widelog.set("order.total_cents", order.totalCents);
  widelog.count("order.items", order.itemCount);

  return Response.json({ orderId: order.id });
};
// src/server.ts
import { serve } from "bun";
import { widelog } from "widelogger";
import { context } from "./logger";
import { checkout } from "./routes/checkout";

serve({
  fetch: (request) =>
    context(async () => {
      const url = new URL(request.url);
      widelog.set("method", request.method);
      widelog.set("path", url.pathname);
      widelog.time.start("duration_ms");

      try {
        const response = await checkout(request);
        widelog.set("status_code", response.status);
        widelog.set("outcome", "success");
        return response;
      } catch (error) {
        widelog.set("outcome", "error");
        widelog.set("status_code", 500);
        widelog.errorFields(error);
        return Response.json({ error: "checkout failed" }, { status: 500 });
      } finally {
        widelog.time.stop("duration_ms");
        widelog.flush();
      }
    }),
});

Instead of scattered console.log calls, each request produces a single JSON log line containing service metadata, user info, order details, timing, and outcome.

You can see full working examples in the examples/ directory for Bun, Express, Hono, and Fastify.

Dot Notation

Keys use dot notation which expands to nested objects in the output. Keys are type-checked at compile time — empty strings, leading/trailing dots, and double dots are all rejected.

widelog.set("user.id", "usr_123");
widelog.set("user.plan", "premium");
// Output: { user: { id: "usr_123", plan: "premium" } }

Bulk Fields

setFields accepts a nested object and recursively flattens it into individual set calls. Non-primitive values (other than plain objects) are silently ignored.

widelog.setFields({
  user: { id: "usr_123", plan: "premium" },
  status_code: 200,
});
// Equivalent to:
// widelog.set("user.id", "usr_123");
// widelog.set("user.plan", "premium");
// widelog.set("status_code", 200);

Measured Timing

time.measure wraps a sync or async callback, automatically recording start and stop times. It returns the callback's result and still records timing even if the callback throws.

const order = await widelog.time.measure("db_ms", () =>
  processOrder(userId),
);

Log Routing

Events with status_code >= 500 or outcome === "error" are emitted at error level. Everything else is info. In development, logs are pretty-printed; in production, they're structured JSON.

API

widelogger(options)

Creates a logger instance. Returns { context, destroy }.

Option Type Description
service string Service name (required)
defaultEventName string Event name included in every log (required)
version string Service version
commitHash string Git commit hash (defaults to "unknown")
instanceId string Instance identifier (defaults to process.pid)
environment string Environment name (defaults to NODE_ENV)
level string Log level (defaults to LOG_LEVEL env or "info")

context(fn)

Run a function inside an isolated async context. All widelog calls within this function (and any functions it calls) are scoped to this context. Supports both sync and async callbacks.

widelog

Imported directly from "widelogger". All methods operate on the current async context established by context().

Method Description
set(key, value) Set a field value (last write wins)
setFields(fields) Recursively flatten a nested object into dotted-key set calls
count(key, amount?) Increment a counter (default +1)
append(key, value) Append a value to an array
max(key, value) Track the maximum value for a key
min(key, value) Track the minimum value for a key
time.start(key) Start a timer
time.stop(key) Stop a timer and record elapsed ms
time.measure(key, fn) Time a sync or async callback, returns the callback's result
errorFields(error, opts?) Extract error name, message, and stack
flush() Aggregate all operations and emit the event

All methods are safe no-ops when called outside a context().

destroy()

Flushes the underlying Pino logger and closes transports. Call this on graceful shutdown.

Contribute

Feel free to contribute to the repository. Pull requests and issues with feature requests are super welcome!

About

Better logging through the accumulation of context throughout a request lifecycle, built on Pino and AsyncLocalStorage.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages