@lp-labs/structured-logging
v0.1.0
Published
Bounded, explicit structured-logging utilities with injected adapters and deterministic policies.
Readme
@lp-labs/structured-logging
Allowlisted scalar logging with pre-sink redaction, injected sampling and bounded buffering. Independent MIT package, Node >=18, zero runtime/peer dependencies, ESM/CJS and strict typings.
Install and quickstart
npm install @lp-labs/structured-loggingimport { createLogger, LogSinkError } from '@lp-labs/structured-logging';
const logger = createLogger({
allowlist: { checkout: ['traceId', 'email', 'amount'] },
redact: ['email'],
sample: (record) => record.level !== 'debug',
sink: (records) => console.log(JSON.stringify(records)),
});
logger.log('checkout', 'info', { traceId: 'opaque-id', email: 'private', amount: 20 });
console.log(logger.pending());
try {
console.log(await logger.flush());
} catch (error) {
if (!(error instanceof LogSinkError)) throw error;
console.log(error.message);
}
logger.clear();CommonJS: const { createLogger } = require('@lp-labs/structured-logging').
API and types
LogScalar = string | number | boolean | null; numbers must be finite.LogLevel = 'debug' | 'info' | 'warn' | 'error'.LogRecord: readonlyevent: string,level: LogLevel,fields: Readonly<Record<string, LogScalar>>. Records, fields and sink batches are frozen.LoggingOptions: requiredallowlist: Readonly<Record<string, readonly string[]>>,sink: (records: readonly LogRecord[]) => void | Promise<void>. Optionalredact: readonly string[]replaces matching field values with[REDACTED]; optionalsample: (record: LogRecord) => booleansees only sanitized records. Sampling is injected, not probabilistic by default; false skips buffering.createLogger(options: LoggingOptions): Logger.Logger.log(event: string, level: LogLevel, fields?: Readonly<Record<string, unknown>>): booleanvalidates, redacts, samples, then queues a snapshot. Default fields{}. Unknown events/fields reject rather than silently dropping keys.pending(): number,clear(): void,flush(): Promise<number>. Flush snapshots the pending batch and returns its length on success; an empty flush returns zero. Concurrent flushes share the same promise. Logging during a flush stays queued. Clear does not cancel an in-flight sink; success removes only original batch objects.LogSinkError extends Error: sink exceptions/rejections are replaced with this fixed diagnostic, without original exception orcause. The sanitized batch stays for retry unless explicitly cleared.
Errors, customization and limits
Fields must be plain records of enumerable string-keyed data properties: no accessors,
symbols, nested values, nonfinite numbers or class instances. Redacted values are replaced
before scalar validation, so a redacted nested value is not traversed or retained.
Accessors are rejected without being invoked. Prototype-like field names are safe.
Diagnostics never interpolate original input values, event/field names or callback errors.
Sampler failures become a fixed Error; nonboolean results and invalid shapes/policies
throw TypeError. Exceeded capacities throw RangeError without enqueuing partial records.
Options are copied at construction. Allowlist: 1–256 events, at most 128 unique fields each;
redaction list at most 128 names; all labels 1–128 UTF-16 units.
maxRecords default 100, range 1–100000; maxBytes default 65536, range 1–10000000;
maxStringLength default 256, range 1–16384 UTF-16 units. Byte accounting is UTF-8 serialized
sanitized record bytes (not array separators or JS heap size). In-flight snapshots duplicate
references, not original secrets; queue/in-flight memory remains O(configured capacity).
Strings preserve Unicode exactly. Overflow rejects; there is no automatic flush or eviction.
Correlate through explicitly allowlisted opaque fields. No free-text message, recursive redaction, timestamp capture, async context, transport retry loop, timeout, backoff or background tasks. Sink delivery may occur before a rejection: retry can duplicate logs. Clear cannot undo delivery. A never-settling sink blocks further flushes; caller owns timeout. Allowlisting is not automatic PII detection; redact sensitive fields and keep event names, IDs and other retained scalars non-sensitive. This is not a confidentiality guarantee for malicious getters/proxies or injected callbacks.
Development
npm ci --offline, npm run build, npm run typecheck, npm test, npm run format,
npm run format:check, npm run prepack. TypeScript ^5.9.3 and Prettier ^3.6.2 are dev-only.
Builds retain dist/esm and dist/cjs; tests import build output and consumers use bare imports.
Support
If this library is useful to you, consider supporting its maintenance with a donation via PayPal.
Author
Created by Libin Prasanth. Connect on LinkedIn for updates and discussion.
