Skip to content

Logging ​

Introduction ​

Logs are how you find out what your application did after the fact. The @plinthjs/logging package gives you a logger with eight severity levels, handlers that decide where records go (memory, console, a file, a file per day), formatters that decide how they look, and a manager that groups handlers into named channels. Every record can carry structured context, so a line says not only what happened but to whom and during which request.

bash
pnpm add @plinthjs/logging

A note on the design: nothing here reads the clock or prints to the console unless you let it. Timestamps come from a clock function you can replace, and console output goes through a function you can replace, so tests are deterministic.

Writing Log Messages ​

A Logger has a channel name and a list of handlers. Each level has a method taking a message and an optional context object.

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

const log = new Logger('app', [new ConsoleHandler()])

log.info('user signed in', { id: 1 })
// [2026-06-08T12:00:00.000Z] app.INFO: user signed in {"id":1}

The line format is [time] channel.LEVEL: message context-as-json, and the context is left out when empty.

Log Levels ​

There are eight levels, from least to most severe:

LevelUse it for
debugDetailed diagnostic information
infoNormal events worth recording
noticeNormal but significant events
warningSomething unexpected that is not an error
errorA failure in the current operation
criticalA failure in a component
alertAction must be taken immediately
emergencyThe system is unusable

Each has a method of the same name (log.warning(...)), and log.log(level, message, context) takes the level as an argument.

ts
log.error('payment failed', { orderId: 42, reason: 'card_declined' })
log.log('critical', 'queue is not draining')

LOG_LEVELS lists the levels in ascending order, isLogLevel(value) is a type guard, and severityOf(level) and meetsThreshold(level, threshold) expose the ordering.

Minimum Level ​

Every handler has a minimum level, its first constructor argument, and ignores anything less severe. This is how you keep noisy debug output out of a production log.

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

const handler = new ArrayHandler('warning')
const logger = new Logger('app', [handler])

logger.info('ignored')
logger.error('captured')
handler.records.length // => 1

Handlers ​

A handler receives each record. These ship with the package.

Console ​

ConsoleHandler formats a record and writes the line to a sink. The default sink is console.log; pass your own to write elsewhere, for example to standard error.

ts
const stderr = new ConsoleHandler('debug', {
  sink: (line) => process.stderr.write(`${line}\n`),
})

A Single File ​

SingleFileHandler(path, level?, options?) appends each line to one file. The directory is created on the first write.

ts
import { SingleFileHandler } from '@plinthjs/logging'

const file = new SingleFileHandler('storage/logs/plinth.log', 'info')

Daily Files ​

DailyFileHandler(directory, basename, level?, options?) writes to a new file each day, named from the record's date: plinth-2026-06-08.log. Because the date comes from the record, rotation follows the logger's clock.

ts
import { DailyFileHandler } from '@plinthjs/logging'

const daily = new DailyFileHandler('storage/logs', 'plinth', 'debug', {
  days: 14, // delete files older than 14 days
  maxFiles: 30, // and keep at most 30 dated files
  extension: '.log', // the default
})

Retention is applied after each write. days removes files dated before the record's date minus that many days, and maxFiles keeps only the newest files. Either one set to 0 or omitted is disabled. Pruning ignores filesystem errors, so a file that cannot be deleted never breaks logging. daily.fileFor(time) returns the path used for a timestamp.

INFO

Dates are UTC. A file's name changes at midnight UTC, whatever the server's time zone.

Stacks ​

StackHandler forwards each record to several handlers. Every child still applies its own minimum level, so one stack can write everything to a file and only errors to the console.

ts
import { StackHandler } from '@plinthjs/logging'

const stack = new StackHandler([
  new SingleFileHandler('storage/logs/plinth.log', 'debug'),
  new ConsoleHandler('error'),
])

stack.pushHandler(new ArrayHandler())

You can also pass several handlers directly to a Logger, which fans out the same way.

Formatters ​

Handlers that produce text take a formatter. LineFormatter is the default. JsonFormatter writes one JSON object per line, which suits log aggregators:

ts
import { JsonFormatter } from '@plinthjs/logging'

const json = new ConsoleHandler('debug', { formatter: new JsonFormatter() })
const jsonFile = new SingleFileHandler('storage/logs/app.json', 'debug', {
  formatter: new JsonFormatter(),
})

log.info('hi', { a: 1 })
// {"level":"info","message":"hi","context":{"a":1},"channel":"app","datetime":"2026-06-08T12:00:00.000Z"}

DailyFileHandler takes a formatter option the same way. A formatter is any object with a format(record): string method, so writing your own is a few lines (see Custom Handlers).

Context ​

Per-Message Context ​

The second argument of every level method is a context object, written out with the message. Keep values serializable.

ts
log.warning('slow query', { ms: 840, table: 'orders' })

Shared Context ​

withContext returns a new logger that adds a base context to every record. The original logger is unchanged, and both share the same handlers. A key in the per-call context beats the same key in the shared context.

ts
const scoped = log.withContext({ requestId: 'abc' })

scoped.info('handled') // context: { requestId: 'abc' }
scoped.error('failed', { code: 1 }) // context: { requestId: 'abc', code: 1 }

log.shareContext({ ... }) merges context into the logger itself, in place, so every later record from that logger carries it. log.flushSharedContext() removes it.

The Context Repository ​

For data that should ride on every line and also travel across boundaries, attach a Context repository to a logger. It has visible data that is added to each record and hidden data that never is. See Context for the full API.

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

const context = new Context().add('request_id', 'r-1').addHidden('token', 'secret')
const log = new Logger('app', [new ConsoleHandler()], { contextRepository: context })

log.info('hi', { extra: 1 })
// [..] app.INFO: hi {"request_id":"r-1","extra":1}

From lowest to highest precedence, a record's context is: the repository's visible data, the logger's shared context, the call's own context.

Channels ​

Most applications want named destinations. A LogManager holds a set of channel factories, each returning the handlers for that channel. A channel is built the first time you ask for it and then reused.

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

const manager = new LogManager({
  default: 'stack',
  channels: {
    single: () => [new SingleFileHandler('storage/logs/plinth.log', 'debug')],
    console: () => [new ConsoleHandler('debug')],
    errors: () => [new ArrayHandler('error')],
    stack: () => manager.stack(['single', 'console']).getHandlers(),
  },
})

manager.channel('single').info('hello') // a named channel
manager.channel().debug('uses the default channel') // the default ('stack')

Asking for a channel that is not defined throws Log channel [nope] is not defined.

Stacking Channels ​

manager.stack(['single', 'errors']) returns one logger whose handlers are all the handlers of those channels, so a write goes to each of them.

ts
const both = manager.stack(['single', 'errors'])
both.error('fans out to both')

The second argument names the combined logger's channel (it defaults to stack). A stacked logger is not cached.

Adding Channels at Runtime ​

manager.extend(name, factory) registers or replaces a channel. manager.build(name, handlers) creates and caches a channel from handlers you already have, without a factory.

ts
manager.extend('audit', () => [new SingleFileHandler('storage/logs/audit.log', 'info')])
const adhoc = manager.build('adhoc', [new ArrayHandler()])

Sharing Context Across Channels ​

manager.shareContext(context) adds context to every channel, both those already resolved and those resolved later. This is the way to stamp a request id onto every line without touching each logger.

ts
manager.shareContext({ requestId: 'r1' })
manager.channel('single').info('with rid')
// ... single.INFO: with rid {"requestId":"r1"}

manager.sharedChannelContext() // => { requestId: 'r1' } (a copy)
manager.flushSharedContext() // remove it everywhere

Pass a contextRepository in the manager options to attach one repository to every logger the manager creates:

ts
const manager = new LogManager({ contextRepository: context, channels })

The MessageLogged Event ​

Give a logger (or a manager) a dispatcher and it fires a MessageLogged event for each record, after the handlers have run. The event carries level, message and the merged context. The dispatcher is any object with a dispatch(event) method, so no particular event system is required.

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

const seen: MessageLogged[] = []
const log = new Logger('app', [], {
  dispatcher: { dispatch: (event) => seen.push(event) },
})

log.warning('careful', { a: 1 })
seen[0].level // => 'warning'
seen[0].message // => 'careful'

To feed the event system, whose dispatch takes an event name and a payload, adapt it in one line:

ts
import { Dispatcher } from '@plinthjs/events'

const events = new Dispatcher()
events.listen('log.message', (event) => notifyOnCall(event))

const log = new Logger('app', [handler], {
  dispatcher: { dispatch: (event) => void events.dispatch('log.message', event) },
})

No event object is created when there is no dispatcher.

Writing Custom Handlers ​

A handler is any object with a level, an isHandling(level) method and a handle(record) method. The easiest way to write one is to extend AbstractHandler, which implements the level check. You only write write, which is called for records at or above the handler's level.

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

import type { LogRecord } from '@plinthjs/logging'

class WebhookHandler extends AbstractHandler {
  protected override write(record: LogRecord): void {
    void fetch('https://logs.example.com/ingest', {
      method: 'POST',
      body: JSON.stringify(record),
    })
  }
}

const log = new Logger('app', [new WebhookHandler('error')])
log.error('payment failed', { orderId: 42 })

A LogRecord has level, message, context, channel and time (epoch milliseconds). Handlers are called synchronously, in the order you gave them, so keep write quick and do not let it throw: send slow work to a queue or fire and forget as above.

A custom formatter only needs format:

ts
import type { Formatter } from '@plinthjs/logging'

const upper: Formatter = {
  format: (record) => `${record.level.toUpperCase()} ${record.message}`,
}

new ConsoleHandler('debug', { formatter: upper })

Application Setup ​

The application generated by create-plinthjs-app configures logging in src/config/logging.ts (a default channel, plus single, daily and stderr channel definitions, driven by LOG_CHANNEL, LOG_STACK and LOG_LEVEL) and builds the application logger in src/providers/app-service-provider.ts. The logger is bound in the container under the LOGGER token. It honours LOG_CHANNEL: single appends to storage/logs/plinth.log, daily rotates dated files next to it (keeping days of them), stderr writes to standard error, and stack fans out to the channels listed in LOG_STACK (for example LOG_STACK=single,stderr). An unknown channel or driver throws at boot. The mapping is the loggerFromConfig / handlersFromConfig helpers exported from @plinthjs/logging, so you can use them in your own bootstrap. The HTTP exception handler is wired to report every unhandled error to that logger. See Error Handling.

Resolve the logger from the container where you need it:

ts
import { LOGGER } from '../Providers/AppServiceProvider.js'

const logger = app().make<Logger>(LOGGER)
logger.info('imported users', { count: 120 })

Testing ​

Use arrayLogger to get a logger and the in-memory handler together, then assert on handler.records. Pass a fixed clock to now so timestamps are stable.

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

const { logger, handler } = arrayLogger('app', { now: () => 0 })

logger.info('user signed in', { id: 1 })

handler.records[0].message // => 'user signed in'
handler.records[0].context // => { id: 1 }
handler.clear() // reset between assertions

consoleLogger(channel, { sink, now }) builds a logger on a console handler, which is handy for asserting on formatted lines:

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

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'

Both helpers accept the usual logger options (context, contextRepository, dispatcher, now).

Released under the MIT License.