Skip to content

@plinthjs/logging ​

The Plinth logging layer. A PSR-3 / Monolog-style severity ladder, a swappable handler contract (with an in-memory test handler and a console handler), per-channel loggers with shared context, and a manager that resolves named channels and stacks them.

Everything that observes time takes an injected now clock (epoch milliseconds), and the console handler writes through an injected sink - so output and timestamps are deterministic in tests and nothing touches the wall clock or console by surprise.

Usage ​

ts
import { arrayLogger, consoleLogger } from '@plinthjs/logging'

// In-memory logger for tests: assert on `handler.records`.
const { logger, handler } = arrayLogger('app')
logger.info('user signed in', { id: 1 })
handler.records[0].message // 'user signed in'

// Console logger writing through a sink (default console.log).
const log = consoleLogger('web')
log.error('boom', { code: 500 })
// [<iso-time>] web.ERROR: boom {"code":500}

Levels ​

The eight PSR-3 levels, ascending in severity: debug, info, notice, warning, error, critical, alert, emergency. A handler's level is a threshold - it only handles records at or above it.

ts
import { ArrayHandler, Logger } from '@plinthjs/logging'

const handler = new ArrayHandler('warning') // ignore debug/info/notice
const logger = new Logger('app', [handler])
logger.info('ignored')
logger.error('captured')
handler.records.length // 1

Shared context ​

withContext returns a new logger that merges a base context into every record (per-call context wins on collision). The original logger is untouched and handlers are shared.

ts
const scoped = logger.withContext({ requestId: 'abc' })
scoped.info('handled') // context: { requestId: 'abc' }
scoped.error('failed', { code: 1 }) // context: { requestId: 'abc', code: 1 }

Channels and stacks ​

ts
import { ArrayHandler, ConsoleHandler, LogManager } from '@plinthjs/logging'

const manager = new LogManager({
  default: 'stack',
  channels: {
    single: () => [new ConsoleHandler('debug')],
    errors: () => [new ArrayHandler('error')],
  },
})

manager.channel('single').info('hello') // resolve + cache a channel
manager.channel().debug('uses the default channel')
manager.build('adhoc', [new ArrayHandler()]) // on-the-fly logger

// Combine several channels' handlers into one logger.
const log = manager.stack(['single', 'errors'])
log.error('fans out to both')

Deterministic tests ​

Inject a fake clock so record timestamps never depend on the wall clock, and a sink so console output is captured rather than printed:

ts
const lines: string[] = []
const log = consoleLogger('web', { sink: (line) => lines.push(line), now: () => 0 })
log.info('served') // lines[0] === '[1970-01-01T00:00:00.000Z] web.INFO: served'

Released under the MIT License.