Skip to content

Latest commit

 

History

History
182 lines (133 loc) · 7.52 KB

api-reference.md

File metadata and controls

182 lines (133 loc) · 7.52 KB

API Reference

This page provides a detailed reference for the core classes and methods in Zario.

zario(options?: LoggerOptions): Logger

Named factory export from zario and zario/logger. Defaults to console-only synchronous output at info; formatting follows NODE_ENV. No implicit files. Explicit options override factory defaults. The default export remains Logger.

Logger Class

The primary class for creating loggers. Provides error event notification via the 'error' event for transport, aggregator, and enricher failures.

Constructor

new Logger(options?: LoggerOptions)

Static Properties

Logger.defaultTransportsFactory

(isProd: boolean) => TransportConfig[] | null

Overrides environment-based default transport selection.

Logger.retryTransportFactory

(options: RetryTransportOptions) => Transport | null

Factory used when retryOptions is provided on LoggerOptions. Root zario import configures this automatically.

Events

'error'

Emitted when an error occurs in the logging pipeline (transports, aggregators, or enrichers).

  • Payload: { type: string, error: unknown }
  • Types: 'transport', 'aggregator', 'enricher'
logger.on('error', ({ type, error }) => {
  console.error(`Error in ${type}:`, error);
});

Logging Methods

Every level supports (message, metadata?), (metadata, message?), (error, messageOrMetadata?), and (message, error). Object-only calls use an empty message. Direct errors become an err field. TypeScript overloads reject unsupported argument pairs. logWithLevel supports the same calls after level.

  • debug(message, metadata?)
  • info(message, metadata?)
  • warn(message, metadata?)
  • error(message, metadata?)
  • fatal(message, metadata?)
  • boring(message, metadata?)
  • silent(message, metadata?)
  • logWithLevel(level: string, message: string, metadata?: object): Log using a custom level name.

Instance Methods

  • child(context, options?): Logger: shorthand for a child with bound metadata.
  • isLevelEnabled(level): boolean: check before computing expensive metadata.
  • flush(): Promise<void>: await queue, aggregators, then transport flush hooks.
  • close(): Promise<void>: idempotently stop accepting logs, close children, drain work and close owned transports (close, or legacy destroy). Shared parent resources remain open when a child closes. Cleanup continues after errors; the first failure rejects the promise.
  • isClosed(): boolean: true once this logger or an ancestor starts closing.

Logging after close is ignored. Custom transports that launch background work must implement flush() to make it awaitable. An independently created logger sharing the same transport instance must coordinate ownership externally.

createChild(options: LoggerOptions): Logger

Creates a new logger instance that inherits the configuration of the current logger. The new options are merged with the parent's.

  • Prefix is inherited unless explicitly replaced.
  • Context is merged.
  • Transports, Filters, and Enrichers are inherited.

startTimer(name: string): Timer

Starts a performance timer. Returns a Timer object.

  • timer.end(): Ends the timer and logs the duration (e.g., Database query took 150ms).

addFilter(filter: Filter) / removeFilter(filter: Filter)

Dynamically adds or removes a filter from the logger.

addAggregator(aggregator: LogAggregator) / removeAggregator(aggregator: LogAggregator)

Dynamically adds or removes an aggregator.

addEnricher(enricher: LogEnricher)

Adds an enrichment function or object to the structured logging pipeline.

setAsyncMode(enabled: boolean)

Toggles asynchronous logging mode at runtime.

flushAggregators(): Promise<void>

Manually flushes all registered aggregators. Useful before application shutdown.


Timer Object

Returned by logger.startTimer().

  • end(): Calculates elapsed time since startTimer was called and logs it using logger.info(). It is idempotent; subsequent calls do nothing.

Constants & Types

LogLevel

An union type of built-in levels: 'silent' | 'boring' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'.

LoggerRetryOptions

Equivalent to RetryTransportOptions without wrappedTransport. Used in LoggerOptions.retryOptions.

Transport

Interface for log transports. See Transports for implementations.

FileTransportOptions

  • path: string - Target file path.
  • maxSize?: number - Maximum file size before rotation.
  • maxFiles?: number - Maximum number of rotated files to keep.
  • compression?: 'gzip' | 'deflate' | 'none' - Compression type.
  • compressOldFiles?: boolean - Whether to compress old files.

MemoryQueueOptions

  • maxQueueSize?: number - Maximum size of the queue before invoking the overflow strategy. Default: 10000.
  • flushInterval?: number - Interval in milliseconds to flush buffered logs (0 to flush on the next tick via setImmediate). Default: 0.
  • batchSize?: number - Maximum size of the batch to write to transports. Default: 100.
  • overflowStrategy?: 'drop-oldest' | 'drop-newest' | 'sync' - Strategy to use when the queue is full. Default: 'drop-oldest'.

HttpTransportOptions

  • url: string - Remote endpoint.
  • method?: string - HTTP method (default: 'POST').
  • headers?: object - HTTP headers.
  • timeout?: number - Request timeout in ms.
  • retries?: number - Number of retries on failure.
  • forceAsync?: boolean - Force asynchronous behavior even when calling synchronous write() method.

CircuitBreakerTransportOptions

  • threshold?: number - Failure count before tripping circuit breaker (default: 5).
  • timeout?: number - Time in ms to wait in half-open state (default: 60000).
  • resetTimeout?: number - Auto-reset timer in ms.
  • onStateChange?: function - Callback for state changes: (fromState: string, toState: string) => void.
  • onTrip?: function - Callback when circuit trips: (failureCount: number) => void.
  • onReset?: function - Callback when circuit resets: () => void.

DeadLetterQueueOptions

  • transport: Transport - Required. Transport to wrap.
  • maxRetries?: number - Maximum retry attempts (default: 3).
  • retryableErrorCodes?: string[] - Error codes worth retrying (default: network errors).
  • deadLetterFile?: string - File path to store failed logs.
  • onDeadLetter?: function - Callback for captured dead letters: (deadLetter: DeadLetterLog) => void.

DeadLetterLog

Extends LogData with additional dead letter metadata:

  • deadLetterReason: string - Human-readable error message.
  • originalError?: string - Error code from original failure.
  • retryCount: number - Number of retry attempts made.
  • failedAt: Date - When the log failed permanently.

Aggregators

See Advanced Usage for aggregator details.

BatchAggregator(maxSize, flushCallback, maxQueueSize?)

  • maxSize: number - Number of logs to collect before flushing.
  • flushCallback: function - Callback to handle the batch of logs.
  • maxQueueSize?: number - Maximum number of logs to keep in memory queue. Default: 10000.

TimeBasedAggregator(flushInterval, flushCallback, maxQueueSize?)

  • flushInterval: number - Time interval in ms between flushes.
  • flushCallback: function - Callback to handle the batch of logs.
  • maxQueueSize?: number - Maximum number of logs to keep in memory queue. Default: 10000.

← Configuration | Transports →