Reference

API

Every export of the five entry points.

Signatures are abbreviated; the .d.ts files in the package are exact. Everything in the root is also exported by the four subpaths.

@unhingged/logit#

Logging#

ExportSignature
logLogger — the global logger; pretty / JSON console at info until configured
configure(options?)(LoggerOptions | LoggerConfiguration) => Logger — reconfigures log in place
createLogger(options?)(LoggerOptions) => Logger — an independent logger; defaults to a console sink
closeAndFlush()() => Promise<void> — log.close()
Loggerclass, see below
LoggerConfigurationclass — the fluent builder, see Configuration
Operationclass — a timed operation, see below

Logger#

Member
verbose / debug / info / warn / error / fatal(…)(template, ...args) · (error, template?, ...args) · (properties, template?, ...args)
write(level, ...args)the same with the level as a value
isEnabled(level)boolean
forContext(name, value, destructure?) / forContext(properties, destructure?)a logger with bound properties
forSource(source)a logger with SourceContext
child(properties, destructure?)alias of forContext
beginOperation(template, ...args)Operation
operation(options, template, ...args)Operation with completeLevel, abandonLevel, warnAfter
timed(template, fn, ...args)runs fn(op), completes or abandons; returns fn's result
flush() / close()Promise<void>
emit(event)the Sink entry point — a logger is a sink
minimumLevelthe effective level for this logger's source
sourcethe bound SourceContext, if any
sinksreadonly Sink[]

Operation#

elapsed · enrich(name, value, destructure?) · complete() / complete(name, value) · abandon(error?) · cancel() · [Symbol.dispose]() (abandons if unfinished)

Levels#

Export
LogLevel'verbose' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
LEVELSthe six, in order
LEVEL_ORDER, LEVEL_CODES, LEVEL_NUMBERS, SERILOG_LEVEL_NAMESrank · INF codes · pino numbers · Serilog names
parseLevel(input)from any spelling or a pino number; throws on unknown
isLevel(value), levelAtLeast(level, minimum), resolveLevel(levelOrSwitch)
LevelSwitchnew LevelSwitch('info'); .level get / set; .onChange(fn)

Templates and capture#

Export
parseTemplate(text)MessageTemplate — { raw, tokens, holes, positional }, cached
templateHash(text)the eight-hex-digit event type
captureValue(value, operator, options, path?, seen?, depth?)the capture rules
captureError(error, options?)an Error as CapturedError
byTransforming(Type, fn)a DestructuringPolicy
DEFAULT_DESTRUCTURINGthe default DestructuringOptions
typesMessageTemplate, TemplateToken, HoleToken, TextToken, DestructuringOptions, DestructuringPolicy, CapturedError

Events#

Export
LogEventnew LogEvent({ timestamp?, level, template, properties?, error?, traceId?, spanId? }, destructuring)
fieldstimestamp, level, template, properties, error, traceId, spanId
gettersmessageTemplate, sourceContext, eventId, errorProperties
methodsaddPropertyIfAbsent(name, value, destructure?), addOrUpdateProperty(…), removeProperty(name), hasProperty(name), renderMessage(options?), extraProperties()

Context#

Export
LogContextrun(props, fn) · push(props) → handle · current() · frame() · runScope(props, fn) · use(store) · isAsync
diagnosticContextset(name, value) · active
typesContextFrame, ContextStore, ContextHandle

Enrichers#

withProperty(name, value, destructure?) · withProperties(object, destructure?) · withComputed(name, fn, destructure?) · fromLogContext() · withEnvironment(name?) · withTraceContext(getter) · type Enricher = (event) => void

Filters#

byExcluding(pred) · byIncludingOnly(pred) · Matching.fromSource(source) · Matching.withProperty(name, pred?) · Matching.withTemplate(text) · Matching.messageMatches(regex) · sampled(rate, pred?, random?) · rateLimited(max, windowMs, pred?, now?) · type Filter = (event) => boolean

Formatters#

Export
textFormatter({ outputTemplate?, utc?, styles?, tokenStyles? })output templates
prettyFormatter({ colors?, timestamp?, utc?, extras?, source? })the development console
jsonFormatter({ keys?, levelFormat?, message?, template?, eventId?, timestampFormat? })flat JSON
clefFormatter({ renderMessage? })CLEF
resolveFormatter(nameOrFn, defaults?, fallback?)by name
DEFAULT_OUTPUT_TEMPLATE, CLEF_MEDIA_TYPE
renderTemplate(template, properties, options?, renderings?), renderValue(value, format?, options?)
formatDate(date, pattern, utc?), formatNumber(value, format?), formatLevel(level, format?), formatError(error, indent?), toJson(value), jsonReplacer
detectColors(stream?), ansicolour
typesFormatter, FormatName, RenderOptions, ValueStyles, TextFormatterOptions, PrettyFormatterOptions, JsonFormatterOptions, ClefFormatterOptions

Sinks#

Export
consoleSink(options?)format, outputTemplate, colors, utc, stderrFrom, restrictedToMinimumLevel, audit
streamSink(stream, options?)format, outputTemplate, colors, utc, …
memorySink(options?).events, .messages(), .clear(); capacity
callbackSink(fn, options?)
httpSink(options)url, headers, body, formatter, contentType, timeout, fetch + batching
seqSink(options)serverUrl, apiKey + batching
batchingSink(send, options?)batchSize, flushInterval, maxQueue, retries, retryDelay, onError, name; .queued
restricted(sink, level), conditional(pred, sink), audit(sink), mapSink(keyOf, create, options?)wrappers
typesSink, SinkOptions, MemorySink, BatchingSink, BatchingOptions, HttpSinkOptions, SeqSinkOptions, FetchLike, StreamLike

Diagnostics#

selfLog.enable('stderr' \| fn) · selfLog.disable() · selfLog.enabled · selfLog.write(message, error?)

@unhingged/logit/node#

Export
fileSink({ path, format?, outputTemplate?, utc?, rolling?, maxBytes?, retainedFileCount?, mkdir? })a rolling file
withMachineName(), withProcessId(), withProcessInfo()enrichers
interceptConsole(logger, { levels?, source? })routes console.* through the logger; returns a restore function
closeOnExit(logger, { signals?, exit?, crashes? })flush and close on exit; returns a remover
type RollingInterval'none' | 'minute' | 'hour' | 'day' | 'month'

Importing this entry installs an AsyncLocalStorage for LogContext if detection failed.

@unhingged/logit/next#

Export
withLogging(handler, options?)wraps (request: Request, ...args) => Response — route handlers and middleware
createOnRequestError({ logger?, level?, source?, flush? })the onRequestError export for instrumentation.ts
requestDiagnosticsdiagnosticContext under the name the Next docs use
REQUEST_COMPLETION_TEMPLATEthe completion message
typesRequestLoggingOptions, RequestInfo, NextRequestErrorContext, NextErrorRequest, OnRequestErrorOptions

Importing this entry installs an AsyncLocalStorage for LogContext — including on the edge runtime.

@unhingged/logit/express#

Export
requestLogger(options?)(req, res, next) middleware; RequestLoggingOptions + responseHeader, stripQuery
errorLogger({ logger? })(error, req, res, next) middleware
REQUEST_COMPLETION_TEMPLATE
typesIncomingRequest, OutgoingResponse, ExpressRequestLoggingOptions

@unhingged/logit/otel#

Export
otlpHttpSink({ url?, headers?, resource?, scope?, templateAttribute?, timeout?, fetch? } + batching)OTLP/HTTP JSON
otelBridgeSink(provider, { scope?, templateAttribute?, flatten? })to an SDK LoggerProvider
encodeOtlpLogs(events, options?), toAnyValue(value), flattenAttributes(record)the encoding
OTEL_SEVERITYlevel → { number, text }
typesOtlpHttpSinkOptions, OtlpEncodeOptions, OtelBridgeOptions, OtelLoggerProvider, OtelLogger, OtelLogRecord