Skip to content

spectrum ​

@c9up/spectrum: structured logging, with named loggers, child loggers, redaction, serializers and console or file channels. Guide: Logger.

Installation ​

bash
pnpm add @c9up/spectrum

ream configure @c9up/spectrum registers the provider and writes config/logger.ts.

Entry points ​

ImportContents
@c9up/spectrumLogger, LoggerManager, channels, defineConfig, targets, onLog, serializers and types
@c9up/spectrum/providerSpectrumProvider (default export)
@c9up/spectrum/services/mainThe application's logger (default export)
@c9up/spectrum/configureconfigure(), run by ream configure @c9up/spectrum
@c9up/spectrum/testingFakeLogger, a channel that records entries for assertions

Exports ​

@c9up/spectrum ​

ExportKindDescription
LoggerclassA logger: level methods, child loggers, bindings
LoggerManagerclassA Logger for the default logger that also holds the named ones (use())
ConsoleChannelclassWrites to stdout and stderr, pretty or JSON
FileChannelclassAppends JSON lines to a file or a file descriptor, with rotation
defineConfigfunctionTypes config/logger.ts and returns a LoggerManagerConfig
configurefunctionSame as @c9up/spectrum/configure
targetsfunctiontargets() starts a Targets list; targets.file(options?, level?) and targets.pretty(options?, level?) build entries
TargetsclassConditional list of transport targets: push, pushIf, pushUnless, toArray
channelsFromTargetsfunctionchannelsFromTargets(list: readonly TransportTargetOptions[], inheritedLevel?): LogChannel[]
onLogfunctiononLog(listener: LogListener): () => void, observes every written entry; returns the unsubscribe function
clearLogListenersfunctionclearLogListeners(): void, removes every onLog listener
createRustLogBridgefunctioncreateRustLogBridge(logger: Logger, options?: RustLogBridgeOptions): { start(): void; stop(): void }, routes the Rust engine's stderr lines through logger
parseRustLogfunctionparseRustLog(line: string): LogEntry | null, reads a [LEVEL module] message line
stdSerializersconst{ err, req, res }, the standard serializers. req and res read a Node request or response, and also one whose fields are methods (method(), url(), headers(), getStatus()), such as ctx.request and ctx.response
stdTimeFunctionsconst{ epochTime, unixTime, isoTime, nullTime }, values for the timestamp option
logLevelfunctionlogLevel(raw: unknown, fallback?: LogLevelWithSilent): LogLevelWithSilent; unset or empty gives fallback ('info'), a value that is no level throws
isLogLevelWithSilentfunctionisLogLevelWithSilent(value: unknown): value is LogLevelWithSilent
logEntryExtrasfunctionlogEntryExtras(entry: LogEntry): Record<string, unknown>, the merged fields of an entry
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.
LogLeveltype'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
LogLevelWithSilenttypeLogLevel | 'silent'
LogEntryinterface{ level, message, module, correlationId?, timestamp, [key: string]: unknown }, merged fields at the root
LogChannelinterface{ name: string; write(entry: LogEntry): void; close?(): void | Promise<void> }
LogConfiginterfaceOne logger's configuration (see Configuration)
LoggerManagerConfiginterface{ default: string; loggers: Record<string, LogConfig> }
ChildOptionsinterface{ level?, redact?, serializers?, msgPrefix? } for child()
RedactOptionsinterface{ paths: string[]; censor?: string | ((value, path) => unknown); remove?: boolean }
LogSerializertype(value: unknown) => unknown
LogMixintype(mergeObject, level: number, logger) => Record<string, unknown>
LogMethodHooktype(this, args: unknown[], method, level: number) => void
LineWritableinterface{ write(line: string): unknown }, a JSON destination
LogListenertype(entry: LogEntry) => void
TimestampOptiontype'epoch' | 'iso' | 'unix' | boolean | (() => string)
LineFormattersinterface{ level?(label, number): Record<string, unknown>; log?(object): Record<string, unknown> }
ConsoleChannelOptionsinterface{ stream?: 'stdout' | 'stderr' }
FileChannelConfiginterfaceOptions of FileChannel
TransportTargetOptionsinterface{ target: string | LogChannel; options?: Record<string, unknown>; level?: string }
FileTargetOptionsinterfaceOptions of targets.file()
PrettyTargetOptionsinterfaceOptions of targets.pretty()
RustLogBridgeOptionsinterface{ modules?: RegExp }, the modules the bridge claims (default /^ream-/)

Logger ​

new Logger(config: LogConfig, module?: string, correlationId?: string, bindings?: Record<string, unknown>). module defaults to 'app'.

MemberSignatureDescription
trace … fatalinfo(mergingObject: unknown, message?: string, ...values: unknown[]): void
info(message: string, ...values: unknown[]): void
Write at that level. An object is merged at the root of the entry, an Error goes under err, values fill printf tokens. A message followed by exactly one object always merges the object, and the message is written as given, % signs included; a message followed by exactly one Error writes it under err. Tokens: %s, %d, %i, %f, %j, %o, %O, %%. An object that %j, %o or %O writes into the message goes through serializers and redact first. A value no token takes is dropped
silentsame as infoWrites nothing
loglog(level: LogLevel, message: string, ...values: unknown[]): voidWrite at a level given at run time; also takes a merging object first
childchild(bindings?: Record<string, unknown>, options?: ChildOptions): LoggerA logger whose entries carry bindings; module and correlationId in bindings set those fields
bindingsbindings(): Record<string, unknown>Name, child bindings, module and correlationId
setCorrelationIdsetCorrelationId(id: string): voidSet the correlation id on this instance; prefer child() per request
levellevel: LogLevelWithSilent (get/set)This instance's level; setting it does not change the parent or siblings
levelNumberreadonly levelNumber: numberNumeric value of level (info is 30, silent is Infinity)
levelsreadonly levels: { values: Record<string, number>; labels: Record<number, string> }Level labels and values
isEnabledreadonly isEnabled: booleanfalse when the config sets enabled: false
isLevelEnabledisLevelEnabled(level: LogLevel): booleanWhether a line at level would be written for this module
ifLevelEnabledifLevelEnabled(level: LogLevel, callback: (logger: this) => void): voidRun callback only when level is enabled; an async callback's promise is returned

LoggerManager ​

new LoggerManager(config: LoggerManagerConfig) extends Logger: its own methods write through the default logger.

MemberSignatureDescription
useuse(name?: string): LoggerThe named logger (default one without a name), created once and cached; a name that is not a key of loggers throws E_SPECTRUM_UNKNOWN_LOGGER, constructor or __proto__ included
createLoggercreateLogger(name: string, config: LogConfig): LoggerBuild a logger named name, not cached; config is not modified
createcreate(config: LogConfig): LoggerBuild an unmanaged logger from a config

Channels ​

ClassConstructorDescription
ConsoleChannelnew ConsoleChannel(format?: 'pretty' | 'json', options?: ConsoleChannelOptions)format defaults to 'pretty'. Without stream, error and fatal go to stderr and the rest to stdout. Control characters are escaped in pretty output
FileChannelnew FileChannel(config: FileChannelConfig)close(): Promise<void> flushes and closes the file

FileChannelConfig:

OptionTypeDefaultDescription
pathstring—File to append to; the file and its directory are created
fdnumber—An open descriptor to write to instead; never rotated nor closed
appendbooleantruefalse starts the file over on first open
maxSizeBytesnumber10 MiBRotate before the file grows past this
maxFilesnumber5Files kept, the live one included
maxBufferBytesnumber16 MiBBytes held while the disk catches up; past it, lines are dropped and a warn line counts them

@c9up/spectrum/provider ​

ExportKindDescription
defaultproviderSpectrumProvider: builds a LoggerManager from the logger config, fills @c9up/spectrum/services/main, forwards every entry to the events emitter as log:line, and closes the channels on shutdown
SpectrumAppContextinterface{ container, config }, what the provider needs from the application

@c9up/spectrum/services/main ​

ExportKindDescription
defaultconstlogger: Logger, the application's LoggerManager once SpectrumProvider booted; a member read before throws

@c9up/spectrum/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: registers @c9up/spectrum/provider and writes config/logger.ts

@c9up/spectrum/testing ​

ExportKindDescription
FakeLoggerclassA LogChannel that keeps every entry
FakeLoggerPredicateinterface{ containing?: string; dataMatches?(data): boolean }
FakeLoggerPredicateArgtypeFakeLoggerPredicate | ((entry: LogEntry) => boolean)
MemberSignatureDescription
writewrite(entry: LogEntry): voidRecord a deep copy of entry
getLoggedgetLogged(): LogEntry[]Copies of the recorded entries
resetreset(): voidForget every entry
assertLoggedassertLogged(level: LogLevel, predicate?: FakeLoggerPredicateArg): voidThrows unless an entry at level matches
assertNotLoggedassertNotLogged(level: LogLevel, predicate?: FakeLoggerPredicateArg): voidThrows if an entry at level matches
ts
import { Logger } from '@c9up/spectrum'
import { FakeLogger } from '@c9up/spectrum/testing'

const fake = new FakeLogger()
const logger = new Logger({ channels: [fake] })
logger.info({ userId: 1 }, 'signed in')
fake.assertLogged('info', { containing: 'signed in' })

Configuration ​

config/logger.ts, read under the logger key. defineConfig takes { default, loggers }, or one LogConfig that becomes a logger named app. Without a config, the provider builds one app logger at LOG_LEVEL (or info) writing to a pretty console.

ts
import { defineConfig, logLevel, stdSerializers, targets } from '@c9up/spectrum'

export default defineConfig({
  default: 'app',
  loggers: {
    app: {
      level: logLevel(process.env.LOG_LEVEL),
      serializers: { req: stdSerializers.req, res: stdSerializers.res },
      redact: {
        paths: ['req.headers.authorization', 'req.headers.cookie', 'res.headers["set-cookie"]'],
      },
      transport: {
        targets: targets()
          .pushIf(process.env.NODE_ENV !== 'production', targets.pretty())
          .pushIf(process.env.NODE_ENV === 'production', targets.file({ destination: 1 }))
          .toArray(),
      },
    },
  },
})

LogConfig:

OptionTypeDefaultDescription
enabledbooleantruefalse keeps the API callable and writes nothing
namestringthe logger's keyWritten on every entry
levelLogLevelWithSilentLOG_LEVEL, else 'info'Lowest level written; an unknown level throws
channelsLogChannel[]a pretty ConsoleChannelWhere entries go; [] silences the logger; wins over destination and transport
destinationstring | number | LineWritable—JSON lines to a file path, a descriptor or a writable; wins over transport
transport{ targets?: TransportTargetOptions[] } | TransportTargetOptions—Targets turned into channels; each target can carry its own level
modulesRecord<string, LogLevelWithSilent>—Level per module binding
redactstring[] | RedactOptions—Paths replaced by [Redacted] (or the censor), or removed. A path is applied to what the line writes: for an object with a toJSON(), to what toJSON() returns
serializersRecord<string, LogSerializer>err and error serializedTransform a field's value before writing
depthLimitnumber5Depth walked in a value JSON cannot write (a cycle, a BigInt)
edgeLimitnumber100Entries written of such an object or array
messageKeystring'msg'Key of the message in a JSON line
timestampTimestampOption'epoch'How a JSON line writes time
baseRecord<string, unknown> | null{ pid, hostname }Fields on every JSON line; null for none
formattersLineFormatters—Reshape the level part and the merged fields of a JSON line
errorKeystring'err'Key an Error passed to a log call is written under
msgPrefixstring—Written before every message
mixinLogMixin—Fields added to every line, computed per call
mixinMergeStrategy(mergeObject, mixinObject) => Record<string, unknown>merging object winsHow mixin fields and the merging object combine
hooks.logMethodLogMethodHook—Called with each log call's arguments
onChild(child) => void—Called with every child logger created

targets.file(options, level?) takes destination (a path, or a descriptor such as 1), append, maxSizeBytes, maxFiles and maxBufferBytes, as FileChannel. targets.pretty(options, level?) takes destination (1 or 2) to send every level to one stream. A target may also be a LogChannel.

The options customLevels, useOnlyCustomLevels, levelComparison, nestedKey, crlf and hooks.streamWrite are refused with E_SPECTRUM_UNSUPPORTED_OPTION.

Container bindings ​

TokenResolves to
Logger (class)The LoggerManager built from the logger config
'spectrum.logger'The same LoggerManager
'logger'The same LoggerManager

'spectrum.logger' and 'logger' are declared in ContainerBindings. When the container has an events binding, the provider emits each written entry on it as log:line, after serializers and redaction.

Errors ​

Each code is a class of the errors namespace (import { errors } from '@c9up/spectrum'): a flare Exception with code and status (500 for all of them).

CodeRaised when
E_SPECTRUM_UNKNOWN_LEVELA configured level, a modules level, a target level or logLevel() input is not a level
E_SPECTRUM_UNSUPPORTED_TARGETA transport target is neither targets.pretty(), targets.file() nor a LogChannel
E_SPECTRUM_INVALID_FILE_OPTIONSA file destination is neither a path nor a descriptor
E_SPECTRUM_INVALID_LINE_OPTIONSmessageKey, timestamp, base or formatters is invalid
E_SPECTRUM_INVALID_REDACT_PATHA redact path cannot be parsed
E_SPECTRUM_INVALID_STRINGIFY_LIMITdepthLimit or edgeLimit is not a positive integer
E_SPECTRUM_UNSUPPORTED_OPTIONThe config sets an option spectrum does not support
E_SPECTRUM_LOGGER_NOT_BOUNDAt boot, the container resolves something other than a Logger for the Logger token
E_SPECTRUM_MISSING_DEFAULT_LOGGERA multi-logger config ({ default, loggers }) names no default logger.
E_SPECTRUM_UNKNOWN_DEFAULT_LOGGERThe default logger is not declared in loggers.
E_SPECTRUM_UNKNOWN_LOGGERlogger.use(name) names a logger that is not in loggers.
E_SPECTRUM_NOT_BOOTEDThe services/main logger was used before SpectrumProvider booted.
E_SPECTRUM_ASSERTION_FAILEDFakeLogger.assertLogged / assertNotLogged failed: the captured entries do not match.
E_SPECTRUM_INVALID_PREDICATEA FakeLogger assertion was given an empty containing, which would match every entry.

Migration ​

  • SpectrumError is gone: test error.code, or error instanceof errors.E_SPECTRUM_* with import { errors } from '@c9up/spectrum'.
  • The name of an error is no longer "SpectrumError".
  • logger.info(message, object) now always merges the object as fields, even when the message holds a % token. The message is written as given. To put a value in the message, pass it with a second value or use the object-first form: logger.info({ id }, 'user %s', name).
  • logger.error(message, err) now writes the error under err instead of appending it to the message.
  • printf now follows the upstream rules: a value no token takes is dropped instead of being appended to the message, %s on an object writes [object Object], and %c is no longer a token. Pass extra values as fields instead.
  • An object written by %j, %o or %O is serialized and redacted. %o and %O now write JSON instead of Node's inspected form.
  • stdSerializers.req now reads ctx.request. url is its path, and the query string is written apart under query, parsed. On ctx.response, stdSerializers.res writes the status from getStatus(). A new config/logger.ts wires both serializers. Add serializers: { req: stdSerializers.req, res: stdSerializers.res } to an existing config.
  • A redact path now also matches inside what an object's toJSON() returns. req.headers.authorization now censors the header of a ctx.request logged raw.
  • logger.use(name), the LoggerManager constructor, defineConfig and the provider read a logger name only among the keys of loggers. use('constructor') or a default set to toString now throws. createLogger() no longer writes name into the config you pass.

See also ​