Konsole Class
The main logging class. Works in browser and Node.js.
Constructor
new Konsole(options?: KonsoleOptions)Example
import { Konsole } from 'konsole-logger';
const logger = new Konsole({
namespace: 'MyApp',
level: 'info',
format: 'auto',
maxLogs: 5000,
});Static Methods
getLogger
static getLogger(namespace?: string): KonsoleGets an existing logger by namespace. Creates a new one with a warning if the namespace is not found.
Parameters:
namespace— Namespace to look up (default:'Global')
Example:
const logger = Konsole.getLogger('Auth');getNamespaces
static getNamespaces(): string[]Returns all registered namespace names.
Example:
Konsole.getNamespaces(); // ['Auth', 'API', 'DB']exposeToWindow
static exposeToWindow(): voidExposes a __Konsole debug handle on window for use in browser DevTools. No-op in Node.js.
Example:
Konsole.exposeToWindow();
// In browser console:
// __Konsole.getLogger('Auth').viewLogs()
// __Konsole.getLogger('Auth').setTimestamp('iso')
// __Konsole.listLoggers()
// __Konsole.enableAll()
// __Konsole.setTimestamp('iso') // change all loggers
// __Konsole.disableRedaction(true) // bypass redaction for debuggingenableGlobalPrint
static enableGlobalPrint(enabled: boolean): voidWhen true, forces all loggers to produce output regardless of their individual format or criteria settings. Stored on globalThis — works in both environments.
Example:
Konsole.enableGlobalPrint(true); // All logs print
Konsole.enableGlobalPrint(false); // Restore normal rulesshutdown
static shutdown(): Promise<void>Flushes and destroys all registered loggers. Returns a promise that resolves when every transport has been drained.
Example:
process.on('SIGTERM', async () => {
await Konsole.shutdown();
process.exit(0);
});enableShutdownHook
static enableShutdownHook(): voidRegisters SIGTERM, SIGINT, and beforeExit handlers that automatically flush all transports before the process exits. Node.js only — no-op in browsers. Safe to call multiple times; handlers are registered at most once.
Example:
Konsole.enableShutdownHook();addGlobalTransport
static addGlobalTransport(config: TransportConfig): voidAdds an HTTP transport to every currently registered logger.
Example:
Konsole.addGlobalTransport({
name: 'sentry',
url: 'https://sentry.io/api/123/store/',
filter: (entry) => entry.level === 'error',
});enableContext
static enableContext(): Promise<void>Initializes AsyncLocalStorage for async context propagation. Lazily loads node:async_hooks — Node.js only; no-op in browsers. Idempotent (repeated calls return the same promise).
Call once during app startup, before the first runWithContext:
await Konsole.enableContext();See the Async Context Propagation guide for full usage.
runWithContext
static runWithContext<T>(store: ContextStore, fn: () => T): TRuns fn inside an async scope whose store is merged into every log entry produced by any logger within the scope. Returns fn's result.
Nested scopes merge with parent context; inner keys shadow outer keys. Precedence for log fields is ALS context < child bindings < call-site fields.
Node.js only — in browsers, fn is invoked directly with no context binding.
Parameters:
store—Record<string, unknown>merged into every log entry inside the scopefn— function to run; can be sync or async
Example (Express):
app.use((req, _res, next) => {
Konsole.runWithContext({ requestId: req.id, userId: req.user?.id }, () => next());
});Throws in Node.js if called before enableContext() has resolved.
getContext
static getContext(): ContextStore | undefinedReturns the current async context store, or undefined when no scope is active.
Konsole.runWithContext({ requestId: 'r1' }, () => {
Konsole.getContext(); // { requestId: 'r1' }
});
Konsole.getContext(); // undefinedInstance Methods — Logging
trace
trace(...args: unknown[]): voidLevel 10. Extremely verbose; disabled by default at level: 'debug' and above.
debug
debug(...args: unknown[]): voidLevel 20. Developer-facing detail; hidden at level: 'info' and above.
info
info(...args: unknown[]): voidLevel 30. General informational messages.
log
log(...args: unknown[]): voidAlias for info(). Level 30.
warn
warn(...args: unknown[]): voidLevel 40. Something unexpected but recoverable.
error
error(...args: unknown[]): voidLevel 50. An operation failed. Written to stderr in Node.js.
fatal
fatal(...args: unknown[]): voidLevel 60. Unrecoverable failure. Written to stderr in Node.js.
Calling conventions
All log methods accept four argument styles:
// 1. Simple string
logger.info('Server started');
// 2. String + fields object (recommended)
logger.info('Request received', { method: 'GET', path: '/users', ms: 42 });
// 3. Object-first: object with msg key
logger.info({ msg: 'Request received', method: 'GET', path: '/users' });
// 4. Error — message extracted, error stored in fields.err
logger.error(new Error('Connection refused'));Instance Methods — Child Loggers
child
child(bindings: Record<string, unknown>, options?: KonsoleChildOptions): KonsoleCreates a child logger that inherits this logger's level, format, transports, and circular buffer. bindings are merged into every log entry the child produces. Bindings accumulate through nested children; call-site fields override bindings on key collision.
Children are not registered in Konsole.instances.
Parameters:
bindings— Key-value pairs attached to every entryoptions.namespace— Override namespace (default: parent's namespace)options.level— Override minimum level (default: parent's level)options.timestamp— Override timestamp format (default: parent's format)options.redact— Additional field paths to redact (merged with parent's — see Redaction)
Example:
const req = logger.child({ requestId: 'abc', ip: '1.2.3.4' });
req.info('Request started', { path: '/users' });
// → INF [App] Request started requestId=abc ip=1.2.3.4 path=/users
const db = req.child({ component: 'db' }, { namespace: 'App:DB' });
db.debug('Query', { sql: 'SELECT...', ms: 4 });
// → DBG [App:DB] Query requestId=abc ip=1.2.3.4 component=db sql="SELECT..." ms=4Worker-mode bindings: when the parent logger was constructed with useWorker: true, child() runs a structuredClone probe over bindings and throws TypeError if they aren't structured-cloneable (functions, symbols, class instances with private fields, etc.). This converts what would otherwise be a confusing crash on the first log call into a clear error at the call site. Circular references are fine — structuredClone handles them natively.
Instance Methods — Configuration
setLevel
setLevel(level: LogLevelName): voidChanges the minimum log level at runtime. Entries below the new level are discarded immediately.
Throws TypeError when given a name that isn't one of 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'. The logger.level = … setter delegates to this method, so it has the same validation.
Example:
logger.setLevel('error'); // only error and fatal from now on
// Bad input fails loudly instead of silently breaking the threshold:
logger.setLevel('verbose');
// → TypeError: [Konsole] Invalid log level: "verbose". Expected one of: trace, debug, info, warn, error, fatal.setTimestamp
setTimestamp(opts: TimestampFormat | TimestampOptions): voidChanges the timestamp format at runtime. Recreates the internal formatter with the new format. Accepts a preset string, a custom function, or a full TimestampOptions object.
Example:
logger.setTimestamp('iso');
logger.setTimestamp('unixMs');
logger.setTimestamp({ format: 'iso', highResolution: true });
logger.setTimestamp((d) => d.toLocaleString('ja-JP'));setCriteria (deprecated)
setCriteria(criteria: Criteria): voidUpdates the output filter at runtime. Prefer setLevel() for threshold-based filtering.
Example:
logger.setCriteria((entry) => entry.level === 'error');addTransport
addTransport(transport: Transport | TransportConfig): voidAdds a transport to this logger. Accepts both Transport instances and plain TransportConfig objects (auto-wrapped in HttpTransport).
Example:
import { FileTransport } from 'konsole-logger';
logger.addTransport(new FileTransport({ path: '/tmp/debug.log' }));
// Plain config — auto-wrapped in HttpTransport
logger.addTransport({
name: 'backend',
url: 'https://logs.example.com/ingest',
});flushTransports
flushTransports(): Promise<void>Immediately flushes all pending batches across every transport.
Example:
window.addEventListener('beforeunload', () => {
void logger.flushTransports();
});Instance Methods — Log Retrieval
getLogs
getLogs(): ReadonlyArray<LogEntry>Returns all stored log entries synchronously.
Example:
const errors = logger.getLogs().filter((e) => e.level === 'error');getLogsAsync
getLogsAsync(): Promise<ReadonlyArray<LogEntry>>Returns all stored entries asynchronously. When useWorker: true, retrieves from the background worker (Web Worker in browsers, worker_threads in Node.js); otherwise equivalent to getLogs().
clearLogs
clearLogs(): voidRemoves all stored entries and resets the viewLogs() cursor.
viewLogs
viewLogs(batchSize?: number): voidDisplays stored entries in batches via console.table. Primarily a browser dev tool.
Parameters:
batchSize— Entries per call (default:defaultBatchSize)
resetBatch
resetBatch(): voidResets the viewLogs() pagination cursor to the beginning.
getStats
getStats(): { logCount: number; maxLogs: number; memoryUsage: string }Returns buffer usage statistics.
Example:
logger.getStats();
// { logCount: 1234, maxLogs: 10000, memoryUsage: "1234/10000 (12.3%)" }destroy
destroy(): Promise<void>Flushes and destroys all transports, stops the cleanup interval, and removes this logger from Konsole.instances.
Example:
await logger.destroy();