Structured JSON Logger With Context

Write newline-delimited JSON logs with levels, child context, timestamps, and safe serialization of errors, circular data, and BigInt.

JavascriptResilience

Code

javascriptsnippet
139 lines
const LEVELS = Object.freeze({ debug: 10, info: 20, warn: 30, error: 40 });

function serializeError(error, seen) {
  if (seen.has(error)) return "[Circular]";
  seen.add(error);
  try {
    const output = { name: error.name, message: error.message };
    if (typeof error.stack === "string") output.stack = error.stack;
    if (error.cause !== undefined) {
      output.cause =
        error.cause instanceof Error
          ? serializeError(error.cause, seen)
          : toSerializable(error.cause, seen);
    }
    return output;
  } finally {
    seen.delete(error);
  }
}

function toSerializable(value, seen = new WeakSet()) {
  if (typeof value === "bigint") return value.toString();
  if (value instanceof Error) return serializeError(value, seen);
  if (value === null || typeof value !== "object") return value;
  if (seen.has(value)) return "[Circular]";
  seen.add(value);
  try {
    if (Array.isArray(value)) {
      return value.map((item) => toSerializable(item, seen));
    }
    if (value instanceof Date) return value.toISOString();
    if (value instanceof Map) {
      return [...value.entries()].map(([key, item]) => [
        toSerializable(key, seen),
        toSerializable(item, seen),
      ]);
    }
    if (value instanceof Set) {
      return [...value].map((item) => toSerializable(item, seen));
    }
    const output = Object.create(null);
    for (const [key, item] of Object.entries(value)) {
      if (key === "__proto__") continue;
      output[key] = toSerializable(item, seen);
    }
    return output;
  } finally {
    seen.delete(value);
  }
}

function safeStringify(value) {
  return JSON.stringify(toSerializable(value));
}

export function createLogger(options = {}) {
  const {
    level = "info",
    base = {},
    write = (line) => process.stdout.write(`${line}\n`),
    now = () => new Date().toISOString(),
  } = options;
  if (!(level in LEVELS)) {
    throw new RangeError(`unknown log level: ${level}`);
  }
  if (base === null || typeof base !== "object" || Array.isArray(base)) {
    throw new TypeError("base must be a plain object");
  }
  if (typeof write !== "function" || typeof now !== "function") {
    throw new TypeError("write and now must be functions");
  }

  const emit = (entryLevel, message, fields = {}) => {
    if (LEVELS[entryLevel] < LEVELS[level]) return;
    if (fields === null || typeof fields !== "object" || Array.isArray(fields)) {
      throw new TypeError("fields must be a plain object");
    }
    let line;
    try {
      const entry = {
        ...base,
        ...fields,
        timestamp: now(),
        level: entryLevel,
        message: String(message),
      };
      line = safeStringify(entry);
    } catch (error) {
      line = JSON.stringify({
        timestamp: now(),
        level: "error",
        message: "failed to serialize log entry",
        error: error instanceof Error ? error.message : String(error),
      });
    }
    write(line);
  };

  return Object.freeze({
    level,
    log: emit,
    debug: (message, fields) => emit("debug", message, fields),
    info: (message, fields) => emit("info", message, fields),
    warn: (message, fields) => emit("warn", message, fields),
    error: (message, fields) => emit("error", message, fields),
    child(bindings) {
      if (
        bindings === null ||
        typeof bindings !== "object" ||
        Array.isArray(bindings)
      ) {
        throw new TypeError("child bindings must be a plain object");
      }
      return createLogger({
        level,
        base: { ...base, ...bindings },
        write,
        now,
      });
    },
  });
}

const logger = createLogger({
  level: "info",
  base: { service: "billing", env: "test" },
});
const requestLogger = logger.child({ requestId: "req-42" });
requestLogger.info("request received", { method: "GET", path: "/invoices" });
requestLogger.warn("slow upstream", { durationMs: 812, attempt: 2 });
requestLogger.error("upstream failed", {
  error: new Error("socket hang up"),
  meta: { retryable: true },
});
logger.debug("filtered out");

const circular = { name: "node" };
circular.self = circular;
requestLogger.info("circular payload", { circular, big: 9007199254740993n });

How it works

Count the functions emit, serializeError, toSerializable and safeStringify as the entire surface area of Structured JSON Logger With Context.

Iteration happens inside for (const [key, item] of Object.entries(value)) — everything outside it runs once. The failure path is explicit — RangeError and TypeError is raised when the guard condition holds.

The return value is newly constructed — inputs are never handed back.

Caveats

  • The guard typeof value === "bigint" short-circuits the flow with an early return when its condition holds.

Using it

The main signature reads export function createLogger(options = {})

createLogger is the public entry point; everything else in the file exists to support it.

Key statements

return [...value].map((item) => toSerializable(item, seen));
return value.map((item) => toSerializable(item, seen));
return JSON.stringify(toSerializable(value));

Interactive Tools for This Topic

FAQ

Does `createLogger` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What happens if the preconditions do not hold?
It throws `RangeError` and `TypeError` before any real work runs, via the guard `typeof value === "bigint"` — handle it at the call site or let it propagate deliberately.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `emit`, `serializeError`, `toSerializable` at load time.