Structured Logger with Children
Medium · Logging
Loggers like pino write one JSON object per line and support child loggers that add context (like a request id) to every line. Write createLogger(bindings, level, output) returning an object with debug, info, warn, error and child.
- Level order: debug < info < warn < error. A logger with level "warn" only writes warn and error. Level "silent" writes nothing.
- logger.info(msg, fields?) pushes JSON.stringify({ level: "info", ...bindings, ...fields, msg }) to the output array (use exactly this key order).
- logger.child(extraBindings) returns a new logger with the same level and output, and bindings { ...bindings, ...extraBindings }. The parent must not change.
The driver runLogger(level, ops) is already written. It creates a root logger with bindings { app: "api" }, runs ops like ["child", "root", "req", { reqId: "r1" }] or ["info", "req", "message", fields?], and returns the output lines.
Next: Koa-style compose()