Skip to content
distributed-systemsPublic

About

better logging for node.js

Resources

Stars

2 stars

Watchers

1 watching

Forks

Latest commit

 

History

82 Commits

Folders and files

Repository files navigation

logd

Modular logging for Node.js and the browser: namespaced loggers, log levels, optional argv-based toggling on Node, and a hook for test runners or custom transports.

npm

Install

npm install logd

The package is ESM ("type": "module"). Use import syntax (or dynamic import()).

From the pnpm workspace at dev/ (see /home/lina/dev/pnpm-workspace.yaml): run pnpm --filter logd test. That runs section-tests with V8 precise coverage and writes coverage/lcov.info. The workspace sets overrides.logd to workspace:logd so every consumer (including section-tests and logd-console-output) type-checks against this package instead of the npm logd@5.3.0 stub.

Optional CI gate: add --coverage-min=<n> to the section invocation in package.json once you want a failing threshold.

Quick start

Use the default export once at startup. It is a singleton (one instance per Node process or browser window).

import logd from 'logd';

const log = logd.module('my-service');

log.info('server listening', { port: 8080 });
log.error('request failed', err, { path: '/api' });

Pass any number of arguments to each log method; values are rendered by the built-in output (Node: logd-console-output; browser: console with basic styling).

Security: redaction (default on)

Before a message reaches the console, named sinks, registerLogSink, or the preload queue, logd builds an outbound copy of the payload:

  • No mutation of caller-owned objects and no live references to them on the outbound message (values are snapshotted).
  • Built-in key catalogue (passwords, tokens, PII-ish fields, healthcare-related names, infra secrets) plus bounded string patterns (JWT, Bearer, query tokens, provider-style API keys, PEM blocks, and more).
  • Fail closed: accessors are not invoked (descriptor snapshot only); uninspectable properties become diagnostic tokens; traversal and string budgets are enforced globally per message.

Default limits (per outbound message)

Limit Default
Single string length 4,096 UTF-16 code units
Total string content 32,768
Object depth 10
Array elements (per array) 100
Object own keys (per object) 100
Visited nodes (total) 2,000
Error stack string 8,192 chars (truncated before line redaction)

When a limit triggers, the affected value is replaced with a structured [REDACT-LIMIT:…] (or similar) diagnostic — the engine does not truncate a long secret and leak the tail.

Public helpers (optional)

import logd, { redactForLog, setRedactionDisabled, REDACTION_LIMITS } from 'logd';

// Same snapshot + masking rules as the logger (for tests or custom pipelines)
const safe = redactForLog({ authorization: 'Bearer xyz' });

// Emergency escape hatch — logs raw caller references (unsafe). Default is redaction **on**.
setRedactionDisabled(true);

Honest limitations: Redaction is best-effort. Arbitrary secrets inside unstructured text may not match every pattern; full clinical de-identification is not guaranteed. Treat logs as non-sensitive only after your own review.

API overview

logd (default export)

Method Description
module(name: string) Returns a LogdModule for that namespace.
enableLogs() Turn logging on programmatically.
disableLogs() Turn logging off programmatically.
addLogSink(id, sink) Node only. Register a named sink. Multiple sinks may be registered; each receives every message that passes filters (see Log sinks (Node)).
removeLogSink(id) Node only. Remove a named sink by id. Returns whether a sink was removed.
registerLogSink(sink, consoleMode?) Node only. Register a single “legacy” callback (each call replaces the previous). See Log sinks (Node).
logMessage(message: LogMessage) Low-level: enqueue a LogMessage built manually (advanced use).

Imported from the same package:

import logd, { LogMessage } from 'logd';

LogdModule

Returned by logd.module('name').

Method Description
trace(...items) Log at debug severity (alias).
debug(...items) Debug.
notice(...items) Notice.
info(...items) Info.
log(...items) Same as info.
warn(...items) Warning.
error(...items) Error.
fatal(...items) Fatal.
wtf(...items) “WTF” / critical.
success(...items) Success (styled).
highlight(...items) Highlight (styled).
child(data) New module with the same name and merged context ({ ...parentData, ...data }).
getData() Context object for this module instance (if any).

Log levels (severity order)

From lowest to highest numeric threshold:

debug → notice → info → warn → error → fatal → wtf → success → highlight

If you set a minimum level, messages below that level are dropped—unless they include an Error instance (see Errors always surface).


Node.js

Enable via command line

Logging is considered on if process.argv contains --log or -l (short form).

node myscript.js --log
node myscript.js --l

Minimum log level via argv

  • Explicit: --level=<name> where <name> is a level, e.g. --level=debug, --level=warn.
  • Shorthand: --<name> for a level, e.g. --warn, --debug (any argv entry that is exactly -- + a known level name).

Examples:

node myscript.js --l --warn
node myscript.js --log --level=debug

If you enable logging with --log or --l without any level flag, the minimum level is 0, so all severities from debug upward are emitted (unless you change level programmatically).

Programmatic enable/disable

import logd from 'logd';

logd.enableLogs();
logd.disableLogs();

Use this when argv control is not enough (e.g. tests, feature flags).

Log sinks (Node)

Sinks run after the usual “logging enabled?” and “level high enough?” checks.

Multiple independent sinks (addLogSink)

Use addLogSink when several handlers should receive the same messages (for example OpenTelemetry, test capture, and a custom forwarder). Each sink is registered with a unique string id; sinks do not need to call each other. Duplicate id throws (nothing is replaced silently).

Dispatch order per message: all named sinks (in insertion order), then registerLogSink if set, then console output (unless registerLogSink used replace).

import logd, { LogMessage } from 'logd';

logd.enableLogs();

logd.addLogSink('otel', (message: LogMessage) => {
  /* emit to OpenTelemetry */
});

logd.addLogSink('tests', (message: LogMessage) => {
  /* assertions or IPC */
});

logd.removeLogSink('tests');

Single legacy sink (registerLogSink)

registerLogSink registers one callback per Logd instance: each call replaces the previous. Use it to capture structured output in tests or forward lines to a parent process.

import logd, { LogMessage } from 'logd';

logd.enableLogs();
logd.registerLogSink((message: LogMessage) => {
  message.getModuleName();
  message.getLogLevel(); // { level, value }
  message.getValues();
  message.hasErrorObject();
}, 'replace');
  • 'mirror' (default): call the sink and still print via the default console transport.
  • 'replace': call the sink only; skip the default console print (typical for CI/workers).

Clear the legacy sink:

logd.registerLogSink(null);

Named sinks from addLogSink are not removed by registerLogSink(null).

Callbacks must not throw; exceptions inside a sink are ignored so logging cannot crash your app.

LogMessage

Use with addLogSink, registerLogSink, or logd.logMessage(new LogMessage(...)) if you construct messages yourself.

Method Description
getModuleName() Namespace string.
getLogLevel() { level, value } for the message.
getValues() Array of arguments passed to the log call.
hasErrorObject() true if any value is an Error.
getCallsite() / hasCallsite() Call site info when present (Node).
createOutboundDispatchCopy(inbound, options?) Static: build the sanitized outbound LogMessage used at the dispatch boundary (default redact: true unless setRedactionDisabled(true) was called).

Errors always surface

If any logged value is an Error, that message is delivered even when logging is disabled or the level would normally filter it out—so failures are harder to miss.


Browser

The package attaches window.__logd (singleton) when bundled for the client. Import as usual:

import logd from 'logd';

const log = logd.module('my-app');
log.info('hello');

Enable or disable from the developer console (persists in localStorage under logd_config):

// enable all levels (default threshold)
window.logd.enable();

// enable and set minimum level by name
window.logd.enable('error');

window.logd.disable();

You can also call logd.enableLogs() / logd.disableLogs() from application code.

Note: registerLogSink is only meaningful on Node; in the browser it is a no-op.


TypeScript

Types are published in dist/index.d.ts. The default export is the shared Logd instance; named export: LogMessage.


Links

About

better logging for node.js

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages