Skip to content

Inspector ​

Introduction ​

@plinthjs/inspector is a debug recorder. While you develop, you want to look back at what your application actually did: which requests came in, which queries they ran and how long those took, which exceptions were thrown, which jobs ran, which mail was sent. The inspector captures each of those observations as a typed entry, stamps it with an id, a batch and a timestamp, and stores it so you can list and filter entries later.

bash
pnpm add @plinthjs/inspector

The recorder class is called Inspector. It is headless: it has no UI and no routes. It records entries into an EntryStore (an in-memory ArrayEntryStore by default) and offers methods to read them back. Building a dashboard, or an endpoint that returns entries as JSON, is up to you.

INFO

The inspector does not subscribe to framework events on its own. Nothing is recorded until your code calls the recorder, typically from a middleware, an event listener, or a log or database hook that you register. This page shows how to wire that up.

Creating a recorder ​

Create one Inspector per application and share it, for example by binding it in a service provider so the container hands the same instance to everyone.

ts
import { Inspector } from '@plinthjs/inspector'

const inspector = new Inspector()

All options are optional:

ts
import { ArrayEntryStore, Inspector } from '@plinthjs/inspector'

const inspector = new Inspector({
  store: new ArrayEntryStore(), // where entries are kept
  now: () => Date.now(), // epoch-millisecond clock
  ids: () => crypto.randomUUID(), // entry id generator
  batchIds: () => crypto.randomUUID(), // batch id generator
})

By default entry ids and batch ids are random UUIDs, so they stay unique across processes (see Persistent Server) and a shared store. Inject ids and batchIds (for example a counter) when a test needs predictable ids. slowQueryMs sets the default threshold for tagging queries slow (100 ms).

Recording entries ​

The recorder has a typed method for each common kind of observation. Every method returns the stored Entry, or undefined when nothing was recorded (recording is paused or a filter rejected the entry).

ts
inspector.recordRequest({ method: 'GET', uri: '/users', status: 200, durationMs: 12 })
inspector.recordQuery('select * from users where id = ?', [1], 3.2)
inspector.recordException(new Error('Payment gateway timed out'))
inspector.recordEvent('user.created', { id: 1 })
inspector.recordJob({ name: 'SendWelcomeEmail', queue: 'default', status: 'processed' })
inspector.recordCache('hit', 'users:1')
inspector.recordMail({ to: ['ada@example.com'], subject: 'Welcome' })
inspector.recordLog('error', 'Could not charge card', { orderId: 5 })

Every method also accepts a trailing tags array to attach extra tags, for example inspector.recordCache('hit', 'users:1', undefined, ['hot']).

What each entry contains ​

An entry is a plain object: { id, batchId, type, content, tags, createdAt }. The type is one of request, query, event, job, cache, mail, notification, exception, log, schedule, model and redis. The content bag depends on the type, and tags are added automatically so you can filter later.

MethodtypecontentAutomatic tags
recordRequestrequestmethod, uri, status, durationMs, headers, payloadmethod:GET, status:200
recordQueryquerysql, bindings, timeMs, slowslow when timeMs is at least 100
recordExceptionexceptionclass, message, stackthe error name, such as TypeError
recordEventeventname, payloadthe event name
recordJobjobname, connection, queue, statusthe job name, status:processed, queue:default
recordCachecacheaction, key, valueaction:hit, key:users:1
recordMailmailto, subject, mailableto:ada@example.com per recipient
recordLogloglevel, message, contextlevel:error

Optional fields you leave out are stored as null (or an empty object for headers, payload and context).

The types notification, schedule, model and redis exist in the vocabulary but have no dedicated method. Record them with the generic record(type, content, tags):

ts
inspector.record('notification', { channel: 'mail', notifiable: 'user:1' }, ['mail'])

Entry builders ​

Each record* method is a thin wrapper around a pure function that turns an input into an EntryDraft ({ type, content, tags }). The builders are exported so you can use them directly, which is how you customise a threshold the recorder methods do not expose. They hold no state and never read the clock.

ts
import { queryEntry, requestEntry } from '@plinthjs/inspector'

queryEntry('select 1', [], 250, 500) // => { type: 'query', content: { ..., slow: false }, tags: [] }
queryEntry('select 1', [], 250) // slowMs defaults to 100: tagged 'slow'

const draft = requestEntry({ method: 'POST', uri: '/orders' })
inspector.record(draft.type, draft.content, draft.tags)

queryEntry(sql, bindings, timeMs, slowMs = 100) takes the threshold directly. inspector.recordQuery(sql, bindings, timeMs, tags?, slowMs?) takes it as its last argument and otherwise uses the slowQueryMs constructor option (default 100).

The full set of builders is requestEntry, queryEntry, exceptionEntry, eventEntry, jobEntry, cacheEntry, mailEntry and logEntry.

Batches ​

Entries that belong to one unit of work, such as a request and everything it triggered, share a batch id. Entries recorded outside any batch use the id default.

withBatch(id, callback) runs a callback with that batch active and restores the previous batch afterwards, even if the callback throws:

ts
inspector.withBatch('req-1', () => {
  inspector.recordRequest({ method: 'GET', uri: '/users', status: 200 })
  inspector.recordQuery('select * from users', [], 4)
})

inspector.entries({ batchId: 'req-1' }) // => the two entries above, newest first
inspector.currentBatch() // => 'default' again

newBatch() generates an id, makes it the current batch for the current async context and returns it. It stays current until endBatch() (or the next newBatch()), so use it only when something else manages the scope; prefer withBatch when the scope has a clear end.

INFO

The batch id is held in AsyncLocalStorage, so it follows async work: with an async callback, entries recorded after an await still land in your batch, and concurrent withBatch calls never see each other's id.

Taggers and filters ​

Register a tagger with tag() to add tags to every entry. It receives the fully stamped entry and returns an array of extra tags, which are merged with the entry's own tags (duplicates are removed).

ts
inspector.tag((entry) => (entry.type === 'request' ? ['api'] : []))

Register a filter with filter() to decide whether an entry is stored. Return false to drop it. A filter sees the entry after taggers have run, and every registered filter must return true.

ts
inspector.filter((entry) => !(entry.type === 'cache' && entry.content['key'] === 'health'))

Both methods return the recorder, so they chain.

Pausing recording ​

Use stopRecording() and startRecording() to switch capture off and on, and recording() to check. While stopped, record returns undefined and stores nothing. withoutRecording(callback) pauses around a callback and restores the previous state afterwards, even on error, which is the right tool for code that would otherwise record itself (for instance, the code that stores or reads entries).

ts
inspector.withoutRecording(() => {
  inspector.recordLog('info', 'never stored')
})

Reading entries ​

entries(filter?) returns stored entries, most recent first. The filter fields are combined with AND, and an omitted field imposes no constraint.

ts
inspector.entries() // everything
inspector.entries({ type: 'query' }) // only queries
inspector.entries({ tag: 'slow' }) // only entries tagged "slow"
inspector.entries({ batchId: 'req-1' }) // one unit of work
inspector.entries({ type: 'request', limit: 20 }) // the 20 most recent requests
inspector.find('entry-3') // one entry by id, or undefined

Pruning and clearing ​

Entries accumulate, so remove old ones regularly. prune(before) removes every entry recorded strictly before an epoch-millisecond instant and returns how many it removed. clear() removes everything.

ts
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000
inspector.prune(oneDayAgo) // => 128

inspector.clear()

Running prune on a schedule is a good fit for task scheduling.

Wiring watchers ​

A watcher is the piece that observes some signal and calls the recorder. The package gives you a small contract: an object with a name and a register(context) method, and registerWatcher(watcher, context) to run it. What context is depends on the signal you subscribe to.

ts
import { registerWatcher } from '@plinthjs/inspector'
import type { Watcher } from '@plinthjs/inspector'

interface QuerySource {
  onQuery(listener: (sql: string, bindings: unknown[], ms: number) => void): void
}

const queryWatcher: Watcher<QuerySource> = {
  name: 'queries',
  register(source) {
    source.onQuery((sql, bindings, ms) => inspector.recordQuery(sql, bindings, ms))
  },
}

registerWatcher(queryWatcher, mySource)

A request watcher is usually a middleware that times the request and records it once the response exists:

ts
import type { Middleware } from '@plinthjs/http'

const recordRequests: Middleware = async (request, next) => {
  const started = Date.now()
  const response = await next(request)
  inspector.recordRequest({
    method: request.method(),
    uri: request.path(),
    status: response.status,
    durationMs: Date.now() - started,
  })
  return response
}

To capture exceptions, call recordException from your error handler; to capture logs, call recordLog from a logging channel; for events, a wildcard listener on the event dispatcher can call recordEvent.

Writing a custom store ​

ArrayEntryStore keeps entries in memory and loses them when the process stops. To keep them elsewhere, implement the EntryStore interface and pass it as the store option:

ts
import type { Entry, EntryFilter, EntryStore } from '@plinthjs/inspector'

class MyStore implements EntryStore {
  store(entries: Entry[]): void {
    /* append */
  }
  get(filter?: EntryFilter): Entry[] {
    return [] /* newest first, honouring type, tag, batchId and limit */
  }
  find(id: string): Entry | undefined {
    return undefined
  }
  prune(before: number): number {
    return 0 /* remove entries older than `before`, return the count */
  }
  clear(): void {}
}

The recorder calls store once per entry. The interface is synchronous, so a store backed by a database should buffer writes and flush them out of band.

Testing ​

The recorder takes its clock and id generators as options, so tests can assert exact output:

ts
import { expect, it } from 'vitest'
import { Inspector } from '@plinthjs/inspector'

it('records slow queries', () => {
  let n = 0
  const inspector = new Inspector({ now: () => 1000, ids: () => `e${++n}` })

  inspector.recordQuery('select 1', [], 250)

  expect(inspector.entries({ tag: 'slow' })).toHaveLength(1)
  expect(inspector.find('e1')?.createdAt).toBe(1000)
})

When you pass ids without batchIds, batch ids still come from their own random generator, never from the entry id sequence. See Testing for more.

For aggregated numbers (slowest routes, p95 durations) rather than individual entries, see Monitor.

Released under the MIT License.