Skip to content

Configuration ​

createLogger(config) takes a LoggerConfig object. Every option is optional. This page lists each one with its type and default, then explains the two output paths, because they decide which options apply.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'billing',
  environment: 'production',
  traceId: true,
  levelOptions: { level: 'info' },
  redact: { autoDetect: true },
  sampling: { rate: 0.5, perLevel: { debug: 0.1 } },
  gracefulShutdown: { enabled: true, timeout: 5000 },
  transports: { console: { format: 'json' } },
});

await logger.info('ready');

Options at a glance ​

OptionTypeDefaultPurpose
appNamestring'App'Name written into every entry and the text prefix.
environment'development' | 'production''development'Written into every entry as environment.
traceIdboolean | TraceIdConfigtrueInclude a trace ID in entries; object form configures NestJS tracing.
format{ timestamp?, colorize?, json? }see belowText and JSON formatting for the default output path.
silentbooleanfalseDrop every entry.
levelOptions{ level?, levels?, colors? }see belowActive level, custom levels and colors.
fieldsPartial<Record<LogFieldKey, string | boolean>>all shownHide fields in the default output path.
redactRedactConfignoneMask sensitive data before any transport sees it.
namespaceLevelsRecord<string, LogLevelString>nonePer-namespace level overrides.
gracefulShutdownboolean | GracefulShutdownConfigoffFlush on SIGTERM and SIGINT.
samplingSamplingConfignoneRate limiting and sampling.
transportsTransportConfignoneWhere entries go. Setting it replaces the default output.

LoggerConfig also has an index signature ([key: string]: unknown), so unknown keys are accepted without a type error. A misspelled option is silently ignored, so check spelling when something has no effect.

Two output paths ​

What reaches the terminal depends on whether you set transports.

No transportsWith transports
FormatterBuilt into the loggerEach transport formats its own output
Streamerror to stderr, everything else to stdoutConsole transport: error and warn to stderr
format.json, format.colorize, format.timestampApplyIgnored; set format, colorize, timestamp on the transport
fieldsApplyIgnored by transports
Console outputAlwaysOnly if you list console

The default path is the quickest way to get readable development logs. Once you add transports, configure formatting on each transport (see Console transport).

ts
import { createLogger } from 'logixia';

// Default path: format and fields apply.
const dev = createLogger({
  appName: 'api',
  format: { colorize: false, json: true },
});

// Transport path: format lives on the transport.
const prod = createLogger({
  appName: 'api',
  transports: { console: { format: 'json', colorize: false } },
});

await dev.info('default path');
await prod.info('transport path');

appName, environment, silent ​

appName and environment are copied into every entry. silent: true makes every log call return immediately, which is handy in tests.

traceId ​

traceId: true (the default) puts a trace ID on every entry. The ID comes from the active trace scope (for example a request handled by middleware) or, outside any scope, from a UUID generated once per logger instance. Set traceId: false to leave it out. See Tracing.

The object form, TraceIdConfig, is read by the NestJS integration:

FieldTypeDefaultDescription
enabledbooleanrequiredTurn trace handling on or off.
generator() => stringUUID v4Create a trace ID when the request has none.
contextKeystring'traceId'Key used in the async context store.
extractor{ header?, query?, body?, params? } (string or string[])see tracingWhere to read an incoming ID. Merged over the defaults.
responseHeaderstring | false'X-Trace-Id'Response header for the resolved ID; false disables it.

format ​

FieldDefaultDescription
timestamptrueShow the timestamp in text output.
colorizetrueANSI colors in text output.
jsonfalseOne JSON object per line instead of text.

These apply to the default output path only.

levelOptions ​

FieldTypeDefaultDescription
levelstring'info'Minimum level that is logged.
levelsRecord<string, number>error 0, warn 1, info 2, debug 3, trace 4, verbose 5Level names and their priority. Lower is more severe.
colorsPartial<Record<level, LogColor>>error red, warn yellow, info blue, debug green, trace gray, verbose cyanLevel colors.

Available colors: black, red, green, yellow, blue, magenta, cyan, white, gray, grey and the bright* variants (brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite).

levelOptions is replaced, not merged

Passing levelOptions replaces the default levelOptions object. If you set only level, the default colors are gone and built-in levels print uncolored. Pass colors too when you want them. See Log levels for how the active level is resolved, including LOGIXIA_LEVEL and NODE_ENV.

fields ​

fields hides parts of the default text output. A field set to false is hidden; any other value, or leaving it out, shows it.

ts
import { createLogger } from 'logixia';

const logger = createLogger({
  appName: 'api',
  fields: { timestamp: false, traceId: false, payload: true },
});

await logger.info('compact line');

The text formatter reads timestamp, level, appName, traceId, context, message and payload. The type also lists service, timeTaken, userId, sessionId and environment (LogFieldKey), but the text formatter does not render those. You can toggle a field per logger at runtime with enableField(name), disableField(name), isFieldEnabled(name), getFieldState() and resetFieldState(). Each toggle prints a [logixia] notice to stderr.

String values are not format templates. Only false has an effect.

redact ​

Masks sensitive values in the payload and message before they reach any transport. Options: paths, excludePaths, patterns, censor and autoDetect. Full reference in Redaction.

namespaceLevels ​

Per-namespace level overrides, matched against a child logger's context. See Log levels.

gracefulShutdown ​

true, or an object:

FieldTypeDefaultDescription
enabledbooleanrequiredRegister the signal handlers.
timeoutnumber5000Milliseconds to wait for transports to flush.
signalsNodeJS.Signals[]['SIGTERM', 'SIGINT']Signals that trigger the flush.
exit'auto' | 'always' | 'never''auto'Whether logixia ends the process after flushing.

See Graceful shutdown.

sampling ​

FieldTypeDefaultDescription
ratenumber (0 to 1)1Fraction of entries kept.
perLevelRecord<string, number>nonePer-level rates; '*' sets a fallback.
maxLogsPerSecondnumberunlimitedHard cap; error, warn and fatal are exempt.
traceConsistentbooleanfalseKeep or drop all entries of a trace together.
statsIntervalMsnumber60000Interval for the sampling stats line; 0 disables it.
adaptiveAdaptiveSamplingConfignoneBoost the rate when the error rate rises.

See Sampling.

transports ​

KeyTypeDescription
consoleConsoleTransportConfigConsole output.
fileFileTransportConfig or an arrayLog files with rotation.
databaseDatabaseTransportConfig or an arrayPostgreSQL, MySQL, MongoDB or SQLite.
analytics{ mixpanel?, datadog?, googleAnalytics?, segment? }Analytics and observability services.
customITransport[]Any transport instance, including the cloud, OTLP, Slack, Discord and worker transports.

See the transports overview.

Environment variables ​

VariableEffect
LOGIXIA_LEVELOverrides the configured level for the whole process.
LOGIXIA_LEVEL_<NAMESPACE>Overrides the level for loggers whose context's first dot-separated segment matches (db and db.queries both read LOGIXIA_LEVEL_DB).
NODE_ENV, CIChoose a default level when levelOptions has no level (see Log levels).
LOGIXIA_SILENT_INTERNAL=1Silences logixia's own stderr diagnostics, for example in tests.

Released under the MIT License.