Skip to content

API Reference

Exports from loggily

Core

ExportDescription
createLogger(name, config?)Create a conditional logger (includes withEnvDefaults, withSpans, withConfigMetrics)
baseCreateLogger(name, config?)Base logger factory without withEnvDefaults() or withSpans() — for manual composition
createTestLogger(name)Test helper — all levels enabled, console output
pipe(base, ...plugins)Pipe a logger factory through plugins (left-to-right)
withEnvDefaults()Plugin: read defaults from env vars (included by default)
withSpans()Plugin: enable .span() capability (included by default)
withConfigMetrics()Plugin: enable { metrics: true } in config (included by default)

baseCreateLogger does NOT include withSpans() or withEnvDefaults(). Use it when you want full manual control over plugin composition:

typescript
import { baseCreateLogger, pipe, withSpans, withEnvDefaults } from "loggily"

// Manual composition — choose exactly which plugins to include
const myCreateLogger = pipe(baseCreateLogger, withEnvDefaults(), withSpans())

Config Array Elements

The second argument to createLogger is an optional config array:

Element TypeExampleDescription
Config object{ level: "debug", ns: "-sql", format: "json", spans: false }Set scope for subsequent elements
consoleconsole or "console"Console output at current scope
File sink{ file: "/path", level?, ns?, format? }File output with optional overrides
Stage function(event) => event | null | voidTransform, filter, or enrich events
Branch array[{ ns: "metrics" }, { file: "/tmp/m.log" }]Sub-pipeline with own scope
Writable{ write: (data) => void, objectMode?: boolean }Receives raw Event objects by default; Node streams get formatted strings

Pipeline (power users)

ExportDescription
buildPipeline(elements, parentConfig?)Build a pipeline from config array elements

Testing

ExportDescription
createTestLogger(name)All levels, console output
startCollecting() / stopCollecting()Collect span data for analysis
getCollectedSpans() / clearCollectedSpans()Access collected spans
resetIds()Reset span/trace ID counters

Tracing

ExportDescription
setIdFormat(format) / getIdFormat()ID format ("simple" or "w3c")
traceparent(spanData, opts?)Format W3C traceparent header
setSampleRate(rate) / getSampleRate()Head-based sampling rate (0.0-1.0)

Types

ExportDescription
LoggerFull logger interface
SpanLoggerLogger + Disposable + SpanData
ConditionalLoggerLogger with optional methods
SpanDataSpan timing and attributes
LogEvent{ kind: "log", time, namespace, level, message, props? }
SpanEvent{ kind: "span", time, namespace, duration, spanId, traceId, ... }
EventLogEvent | SpanEvent
Stage(event: Event) => Event | null | void
Pipeline{ dispatch, level, dispose }
LogLevel"trace" | "debug" | ... | "silent"
LogFormat"console" | "json"
LazyMessagestring | (() => string)
LoggerFactory(name: string, config?) => ConditionalLogger
LoggerPlugin(factory: LoggerFactory, ctx: PluginCtx) => LoggerFactory
PluginCtxShared context for inter-plugin communication
ConfigElementUnion of all valid config array elements
ConfigObjectScope config: { level?, ns?, format?, spans? }
FileDescriptorFile output: { file, level?, ns?, format? }
WritableAny object with { write, objectMode? }
FileWriter{ write, flush, close }
IdFormat"simple" | "w3c"
TraceparentOptions{ sampled?: boolean }

Deprecated API

These functions still work but are deprecated. They map to environment variables internally:

Export (deprecated)Replacement
.logger(ns?, props?).child(ns?, props?)
setLogLevel(level) / getLogLevel(){ level } in config array or LOG_LEVEL env
setLogFormat(format) / getLogFormat(){ format } in config array or LOG_FORMAT env
enableSpans() / disableSpans() / spansAreEnabled()TRACE=1 env var
setTraceFilter(ns) / getTraceFilter()TRACE=namespace env var
setDebugFilter(ns) / getDebugFilter(){ ns } in config array or DEBUG env
addWriter(fn)Stage functions or { file } in config array
setOutputMode(mode) / getOutputMode()Omit console from config array
setSuppressConsole(bool)Omit console from config array

Exports from loggily/context

ExportDescription
enableContextPropagation() / disableContextPropagation()AsyncLocalStorage context control
isContextPropagationEnabled()Check if context propagation is active
getCurrentSpan()Get current span context
runInSpanContext(ctx, fn)Run function in specific context

Exports from loggily/otel

OpenTelemetry bridge — forwards loggily events to OTLP-compatible backends. Requires @opentelemetry/api as a peer dependency.

ExportDescription
toOtel(options?)Stage that forwards events to OpenTelemetry (transparent — events pass through)
OtelBridgeOptionsOptions: api, loggerName, tracerName, logs, spans
typescript
import * as otelApi from "@opentelemetry/api"
import { createLogger } from "loggily"
import { toOtel } from "loggily/otel"

const log = createLogger("myapp", [toOtel({ api: otelApi }), console])

The stage is transparent — events pass through unchanged to subsequent pipeline elements (like console above). Set logs: false or spans: false to forward only one event type.

Exports from loggily/metrics

Span metrics collection via explicit collectors.

ExportDescription
withMetrics(collector)Wrap a logger to record spans to a collector
createMetricsCollector()Create a standalone metrics collector
SpanStatsStats type: count, min, max, mean, p50, p95, p99

Exports from loggily/worker

ExportDescription
createWorkerLogger(postMessage, ns, props?)Logger for worker threads
workerTransportStage(postMessage)Pipeline stage that forwards via postMessage
handleWorkerEvents(logger)Route worker events to a logger
createWorkerLogHandler()Zero-config main thread handler
createWorkerConsoleHandler(opts?)Console message handler
forwardConsole(postMessage, ns?)Forward console.* from worker
restoreConsole()Restore original console methods
isWorkerMessage(msg)Type guard for any worker message
isWorkerConsoleMessage(msg)Type guard for console messages
isWorkerEvent(msg)Type guard for log/span events
isWorkerLogEvent(msg)Type guard for log events
isWorkerSpanEvent(msg)Type guard for span events