@bazariodev/docket
v1.3.0
Published
Structured diagnostic logging with injected redaction, storage, history, and archive capabilities.
Downloads
333
Readme
@bazariodev/docket
Use Docket to record application events, remove private data, and keep recent records for diagnostics. You can send records to a server or export them as a ZIP file.
Install
pnpm add @bazariodev/docket @bazariodev/winnowThe examples use Winnow for redaction. You can supply your own redactor. Docket installs Coordination for memory history.
Supported Node.js versions are ^22.12.0 || ^24.0.0 || >=26.0.0.
Usage
import { createDocket } from '@bazariodev/docket/client';
import { createRedactor } from '@bazariodev/docket/redaction';
import * as conversion from '@bazariodev/winnow';
const policy = { fields: { password: 'drop', accessToken: 'drop' } };
const redactor = createRedactor(policy, conversion);
const docket = createDocket({ areas: [{ id: 'application' }], redactor });
const logger = docket.getLogger('application', 'Connection');
logger.info('Connection ready');
const records = await docket.history?.query();The client keeps the latest 1,000 records in memory. Console output and upload are off. Use stable scope names such as Connection. Put request IDs in logger.child({ context: { requestId } }).
Redaction
Docket applies the field policy to data, context, and Error properties before a sink receives the record. Field names match at every depth, regardless of case.
- Unknown fields default to
keep. SetunknownFields: 'drop'to keep only the fields you select. Setscopeanddroppedtokeepto retain suppression counts. - Use
dropto remove a field,maskto hide part of a value, orhashwith a hash function you supply. - Text rules also apply to fields you keep. To add a rule, supply a copy of Winnow's
TEXT_RULESwith the new rule. See Server output. Apolicy.textlist replaces all provider text rules. Settext: []to disable all text rules. - For SIP messages, use
createSipTools(TEXT_RULES).redactSipMessage(message, { redactor }). It replaces display names with[redacted]by default.
Storage and delivery options
Set history: { maxRecords } to change the memory limit. Set history: false to turn history off. Use history.query({ areas, from, to }) to select records. Time bounds are inclusive.
History and upload use separate stores. Upload success leaves history available for export. For the IndexedDB example, install Hopper 2 or later. Its IndexedDB clients use Web Locks.
After sign-in, supply the tenant and account key in authenticatedSession.storageKey. Use an opaque key. Bind uploadRecords to that account. Reuse createDocket and redactor from Usage. Open the outbox first. If a later step fails, stop each client you opened.
import { createLogStore } from '@bazariodev/docket/storage';
import { createIndexedDbStore } from '@bazariodev/hopper/indexeddb';
import { createIndexedDbOutbox } from '@bazariodev/hopper/outbox/indexeddb';
const scope = authenticatedSession.storageKey;
const names = (kind) => ({
databaseName: JSON.stringify(['diagnostics', scope, kind]),
lockName: JSON.stringify(['diagnostics-owner', scope, kind]),
});
const storageOptions = { history: names('history'), outbox: names('outbox') };
const outbox = await createIndexedDbOutbox({
...storageOptions.outbox,
maxRecords: 1000,
});
let historyClient;
let persistent;
try {
historyClient = createLogStore(storageOptions.history, createIndexedDbStore);
persistent = createDocket({
areas: [{ id: 'application' }],
redactor,
history: historyClient,
upload: {
outbox,
send: uploadRecords,
},
});
} catch (error) {
const failures = [error];
for (const stop of [() => historyClient?.stop(), () => outbox.stop()]) {
try {
await stop();
} catch (cleanupError) {
failures.push(cleanupError);
}
}
if (failures.length > 1) throw new AggregateError(failures, 'Docket setup failed');
throw error;
}After setup, persistent owns both clients. Give each store its own database. Use the same lock name for all writers to one database. If another tab owns history, Hopper uses memory for that history client. After a storage operation, check historyClient.getStatus().mode. For a memory outbox, use createMemoryOutbox({ maxRecords }) from @bazariodev/hopper/outbox.
Periodic upload
- Set
upload.outboxandupload.sendto enable upload. The default batch limit is 100 records (maxBatchRecords). The upload timer defaults to 5,000 ms (intervalMs). - In
send(records, signal, token), use the supplied abort signal and set a request timeout. Resolve only when the server accepts the entire batch. Deduplicate the token on the server for that account. - Reject the promise on failure. Docket retains the batch and token and pauses automatic upload. Supply
upload.onErrorin the options or checkpersistent.upload.getStatus().paused. Callpersistent.upload.flush()to retry. - Writes continue during a pause. Check
persistent.upload.getStatus().droppedRecordsfor outbox drops and writes lost after a storage failure.
Shutdown and account changes
docket.flush() waits for the sinks to finish work on records written before the call. If a sink calls it during delivery, it includes the current record. Call it again to include later records.
await docket.stop() cancels upload before it flushes the sinks. It preserves stored records and makes no final send. Dispose of browser listeners separately.
Supply an isActive function when you call createDocket. Before you erase the old account's records, make that function return false to block new records. Run these steps in order. Attempt every step even if one fails. Report all failures.
- Call
persistent.resetLevel()while the old account is active. - Stop the sender with
await persistent.upload.stop(). - Clear pending uploads with
await persistent.outbox.clear(). - Release the storage clients with
await persistent.stop(). - Clear local history with
await persistent.history.clear().
Keep the old account's storage names if cleanup needs a retry. Never send its records with another account's credentials.
If modules keep loggers across accounts, keep their createLogging hub alive. Block new records before the switch. Call logging.resetLevel() while the old account is selected. Detach and clean up the old account's sinks. Detaching the last sink resets suppression. If a sink stays attached, call logging.resetStorms() when you switch accounts or clear logs.
If you store level overrides, use one levelStorage adapter that reads and writes the current account's key. Select the new account, then call logging.reloadLevels(). Allow new records after setup.
Migrate storage from 0.0.0
Old clients can leave IndexedDB history and localStorage metadata, even in memory mode. Stop the old clients first. Use the original database name. The managed default was bazario-logging:history:${leaseKey}. The standalone default was bazario-logging.
Acquire the exclusive lock JSON.stringify(['bazario:logging:indexeddb', databaseName]). Hold it until database deletion succeeds or fails. After success, remove the managed metadata key bazario-logging:metadata:${databaseName}. See the storage erasure example.
Output
To add console output, call docket.addSink(createConsoleSink({ level: 'info' })). Import createConsoleSink from the root entry. For a custom sink, accept each record synchronously in write(record). Track pending work in the sink and wait for it in flush(). The function returned by addSink detaches the sink. After detach, you own its cleanup.
Server output
Save this script as server-log.mjs. Run node server-log.mjs or bun server-log.mjs. The sink writes one JSON record per line to stdout. If a new line would take pending output above 1 MiB, the sink drops that line. It reports the first failure to stderr. A drop alone leaves the exit code at 0.
import { Buffer } from 'node:buffer';
import process from 'node:process';
import { createLogging } from '@bazariodev/docket';
import { createRedactor } from '@bazariodev/docket/redaction';
import { createRedactor as createValueRedactor, TEXT_RULES } from '@bazariodev/winnow';
const queryRule = {
name: 'example-query-secret',
pattern: /[?&]api_key=[^&#\s]*/gi,
replace: (match) => `${match.slice(0, match.indexOf('=') + 1)}[redacted]`,
};
const redactor = createRedactor(
{ fields: { route: 'keep' }, unknownFields: 'drop' },
{ createRedactor: createValueRedactor, TEXT_RULES: { exampleQuerySecret: queryRule, ...TEXT_RULES } },
);
const MAX_PENDING_BYTES = 1024 * 1024;
let pendingBytes = 0;
let last;
let failure;
let reported = false;
function fail(error) {
failure ??= error;
last?.resolve();
}
process.stdout.on('error', fail);
const sink = {
write(record) {
if (failure) throw failure;
const line = `${JSON.stringify(record)}\n`;
const bytes = Buffer.byteLength(line);
if (pendingBytes + bytes > MAX_PENDING_BYTES) throw new Error('Log output limit reached');
pendingBytes += bytes;
const done = Promise.withResolvers();
last = done;
function complete(error) {
pendingBytes -= bytes;
if (error) fail(error);
done.resolve();
}
try {
process.stdout.write(line, complete);
} catch (error) {
complete(error);
}
},
async flush() {
await last?.promise;
if (failure) throw failure;
},
};
const logging = createLogging({
areas: [{ id: 'application' }],
redactor,
stormLimit: 100,
sinks: [sink],
onError() {
if (reported) return;
reported = true;
process.stderr.write('Logging failed.\n');
},
});
const log = logging.getLogger('application', 'request');
log.info('Request received', {
route: '/health?api_key=demo-value',
});
log.info('Request complete');
try {
await logging.stop();
} catch {
process.exitCode = 1;
}The HTTP server example stops on SIGTERM or SIGINT. It reports the total drop count and sets a shutdown deadline.
Export and download
Use JSON.stringify(records) for JSON. For NDJSON, write each record as JSON on a separate line. For a ZIP file, install Baler. This browser example uses the client from Usage.
import { downloadBlob } from '@bazariodev/docket/browser';
import { createLogBundle } from '@bazariodev/docket/export';
import * as archive from '@bazariodev/baler';
const files = [{ name: 'application.log', areas: ['application'] }];
const options = { source: docket.history, redactor, files };
const { blob, fileName } = await createLogBundle(options, archive);
downloadBlob(blob, fileName);Export reads one history snapshot. The default maxInputSize is 32,000,000 UTF-8 bytes for all files and the manifest. Clearing history cannot erase downloads or records the server has accepted.
Behavior
- Log levels are
debug,info,warn, anderror. The default isinfo. UsesetLevelfor an override andresetLevelto remove it. Give each account and hub a separatelevelStoragekey. - The default
stormLimitpermits 100 records per area and scope each second. The hub reports further records in alogging.suppressedsummary. SetstormLimit: falseto disable the limit. - Pass a function as log data to calculate it after admission checks. Sinks receive frozen records. For routing flags, use the third argument, for example
{ metadata: { report: false } }. Use up to 16 boolean flags with non-secret names. - Memory history returns a snapshot in admission order. Its capacity limits the number of records. The default redactor limits each record to 65,536 JSON characters.
API
Append the entry to @bazariodev/docket in the import path. The type declarations in the installed package's dist directory list the options and methods.
| Entry | Functions |
| --- | --- |
| Root | createLogging, createConsoleSink, formatRecord |
| /client | createDocket |
| /redaction | createRedactor |
| /history | createMemoryHistory |
| /storage | createLogStore |
| /indexeddb | createIndexedDbLogStore, clearIndexedDbLogStore |
| /upload | createUploadSink |
| /export | createLogBundle |
| /browser | captureGlobalErrors, flushOnPageHide, collectBrowserEnvironment, downloadBlob |
| /sip | createSipTools, describeSipMessage |
| /devtools | installConsoleApi |
Errors
The hub reports failures through onError(error, source). The source is data, redactor, sink, storage, scope, or reentry. If one sink fails, the other sinks still receive the record. Invalid configuration can throw TypeError. Hub flush() and stop() attempt every sink and reject with an aggregate error on failure. Canceling an active upload rejects its pending flush with AbortError.
TypeScript
Docket includes ESM and CommonJS declarations. Import LogRecord, LogOptions, and LogMetadata from the root. Import DocketOptions, HistoryClient, and OutboxClient from /client. The client and upload entries need AbortSignal types. Browser, persistence, and export entries need DOM types.
