How to use xPack Logger
This page is intended for those who plan to use this module within their own projects.
Using the logger
The @xpack/logger module can be used in both TypeScript and JavaScript
Node.js code; the class can be used directly, or a custom class can be
derived from it for a custom behaviour.
The typical use case is to create an instance of the Logger object,
then log messages at different levels:
import { Logger } from '@xpack/logger'
const log = new Logger({
level: 'info'
})
log.info('hello') // Displayed on stdout.
log.debug('world') // Ignored.
When the preparation of a message is expensive, check the log level first (see Log level checks).
Importing the module
In TypeScript and ECMAScript modules, use import:
import { Logger } from '@xpack/logger'
The typings refer to the global Console interface, declared by the
@types/node package, used by the console parameter of the constructor
and by the console accessor, so in TypeScript projects the @types/node
package must be installed, as in any other Node.js project. Without it
(and without the dom library), the compiler reports that it cannot find
the name Console, unless skipLibCheck is enabled.
The typings are found through the exports map of the package by the
TypeScript module resolution modes node16, nodenext, and bundler,
which are the ones to use. The legacy mode node10 (the old default of
the projects with "module": "commonjs") ignores exports, and works only
because package.json still has the legacy main and typings fields.
Support for node10 will be removed in a future major release, by
removing these two fields; projects that still use it should migrate to one
of the modern modes.
The package.json file of the package can be read through the package
name, for example:
require('@xpack/logger/package.json')
The package is an ES module only. In JavaScript with CommonJS, use
require(), which loads ES modules by default in Node.js 22.12 or later
(the minimum version supported by the package):
const { Logger } = require('@xpack/logger')
The module does not use top-level await, so it can be loaded
synchronously. The asynchronous alternative, which is the only possibility
in the versions of Node.js that fail with ERR_REQUIRE_ESM, also works,
inside an async function (CommonJS has no top-level await):
async function main() {
const { Logger } = await import('@xpack/logger')
// ...
}
Log levels
The following strings are recognised as valid level names:
export type LogLevel =
| 'silent'
| 'error'
| 'warn'
| 'info'
| 'verbose'
| 'debug'
| 'trace'
| 'all'
The name of the warning level is warn, like the warn() method; the
messages of this level start with the prefix warning: .
The levels, their numeric values, and their purpose are:
| Level | Value | Used for |
|---|---|---|
silent | 0 | no messages, except those of always() |
error | 10 | errors, and the output of output() |
warn | 20 | warnings |
info | 30 | informative messages, the progress of the application |
verbose | 40 | additional details of the progress |
debug | 50 | the information needed to diagnose a problem |
trace | 60 | the flow of the execution |
all | 70 | everything |
Internally, string levels are converted to numeric values (the
Logger.numericLevels object) for comparison purposes. Higher numeric
values correspond to greater verbosity.
The valid names, in increasing order of verbosity, are available at run
time as the frozen array Logger.levelNames.
The static members Logger.numericLevels, Logger.recommendedLevel,
Logger.numericLevelUndefined, and Logger.numericLevelAlways are
constants, shared by all the loggers: the compiler rejects an assignment
to them, and at run time the Logger class and the numericLevels object
are frozen, so an assignment throws a TypeError. Logger.recommendedLevel
(info) is only the recommended level, for the applications that need one
when none was chosen; the library does not apply it, so a logger created
without a level stays in the preliminary state. Its previous name,
Logger.defaultLevel, is deprecated, and will be removed in the next major
version.
When the level comes from a source that is not checked by the compiler,
like a command line option or an environment variable, validate it with
the type guard Logger.isLogLevel(), which narrows the type of its
argument to LogLevel. It returns false for non-string values, for
strings with a different case ('INFO'), and for the names of inherited
properties ('toString'):
const name = process.env.LOG_LEVEL
if (Logger.isLogLevel(name)) {
log.level = name
} else {
log.error(`Level must be one of: ${Logger.levelNames.join(', ')}`)
}
Assigning an invalid name to log.level, passing it to the constructor,
or passing it to isLevel() throws an error whose message lists the valid
names, for example:
RangeError: Unsupported log level 'verbos'; valid levels are: silent, error, warn, info, verbose, debug, trace, all
- a
RangeErroris thrown for a string that is not a level name, including the empty string, a name with a different case ('INFO'), and the names of inherited properties ('toString'); - a
TypeErroris thrown for a value that is not a string, includingnulland, for the setter andisLevel(),undefined; - a
levelthat isundefinedin the constructor is the same as no level.
The value is written in the message as util.inspect() writes it, so a
newline or an escape character of an untrusted value is escaped.
In TypeScript, the level getter has the type LogLevel | undefined,
since the level is undefined in the preliminary state, but the setter
accepts only a LogLevel: the level cannot be set back to undefined, and
log.level = undefined does not compile. The level and console
properties of the constructor options accept an explicit undefined, also
with the compiler option exactOptionalPropertyTypes, which is the same
as not passing them, so new Logger({ level: process.env.LOG_LEVEL }) can
be written when the value is already checked with Logger.isLogLevel().
Logging methods
All the logging methods, always(), error(), output(), warn(),
info(), verbose(), debug(), and trace(), have the same signature, with
an optional message of any type and further arguments, as accepted by
util.format():
(message?: unknown, ...args: unknown[]): void
The methods differ by the level from which they are written (the threshold), by the console stream, and by a prefix added to the message:
| Method | Written from level | Stream | Prefix |
|---|---|---|---|
always() | every level | stdout | none |
error() | error | stderr | error: |
output() | error | stdout | none |
warn() | warn | stderr | warning: |
info() | info | stdout | none |
verbose() | verbose | stdout | none |
debug() | debug | stdout | debug: |
trace() | trace | stdout | trace: |
Here stdout is console.log() and stderr is console.error(). A method
is written when the log level is equal to or higher than its threshold;
at silent only always() is written. The method error() omits its
prefix when the first argument is an Error (see below).
The three methods that write on stdout without a prefix are used for different purposes:
always()is for the messages that must be shown at every log level, includingsilent, like the version or the result requested by the user;output()is for the normal output of the application, which is suppressed atsilent, together with all the other messages;info()is for informative messages, shown from theinfolevel.
The console
By default, the logger writes on the global console. A different console
can be passed to the constructor, for example a mock console, to capture
the messages in tests:
import { MockConsole } from '@xpack/mock-console'
const mock = new MockConsole()
const log = new Logger({ console: mock, level: 'info' })
log.info('hello')
// The `console` accessor returns the mock, with its own type.
console.log(log.console.outLines)
The logger uses only the log() function, for the standard output, and the
error() function, for the standard error (see the table of the logging
methods above), so any object that has these two functions can be used, not
only a Node.js Console; the TypeScript type is LoggerConsole:
const lines: string[] = []
const log = new Logger({
console: {
log: (message: unknown) => lines.push(`${String(message)}`),
error: (message: unknown) => lines.push(`error: ${String(message)}`),
},
level: 'info',
})
The functions are called as methods of the object, so they may use this.
An object without the log() or the error() function is rejected by the
constructor with a TypeError.
In TypeScript, the class has a type parameter, the type of the console, which
the console accessor returns. Without a console it is the Node.js
Console, so log.console.table() is available; with a minimal object it is
the type of that object, so the compiler does not allow functions that it
does not have; with a mock it is the type of the mock, so its members are
available without a cast. The default type argument keeps the existing code
working: a variable of type Logger, and a class that extends Logger,
mean the logger with the Node.js Console.
Since a logger created without a console uses the global console object,
the console option can be omitted only if that object is of the type of the
logger. For a richer type, like Logger<MockConsole>, the option is
required, and the compiler rejects the constructor call without it.
Log level checks
When the preparation of a message is expensive, check the log level first, so that the work is done only if the message will be written:
if (log.isDebugEnabled) {
const message = invoke_long_method()
log.debug(message)
}
There is a check for each level: isErrorEnabled, isWarnEnabled,
isInfoEnabled, isVerboseEnabled, isDebugEnabled, isTraceEnabled, and
isAllEnabled. Each is true when the messages of its level are written,
that is when the current log level is that level or a higher one; for
example, isInfoEnabled is true at debug. Their previous names
(isError, isWarn, isInfo, isVerbose, isDebug, isTrace, and
isAll) are deprecated, with the same behaviour, and will be removed in the
next major version.
When the log level is not known at compile time, use the generic
isLevel(level) method, which returns true if the current log level
is equal to the given level or higher.
Before a log level is set (the preliminary state), all checks
(isDebugEnabled, isLevel(), and the others) return true. This way, the
messages produced under the check are stored in the internal buffer
rather than lost, and are filtered when the log level is set. Use
hasLevel to tell whether a log level was set.
For example, to ensure that the log level is not decreased, check
hasLevel first, since in the preliminary state there is no level
to compare with:
if (!log.hasLevel || !log.isLevel(newLevel)) {
log.level = newLevel
}
The isSilent accessor is deprecated, since it is always true; to
check for the silent level, use log.level === 'silent'.
Logging errors
Error objects are expanded by util.format(), as by console.log():
the first line has the name and the message (for example Error: boom),
and it is followed by the stack trace and, if present, the cause chain,
on several lines. This is the same in all logging methods, which differ
only by the stream and the prefix.
The caller decides how much of an error is shown:
- to show the full details, including the stack trace, pass the error
object, for example
log.error(err); - to show a single line, pass only its message, for example
log.error(err.message).
The prefix depends on the method and on the position of the error:
| Call | Output (first line) | Stream |
|---|---|---|
log.error(err) | Error: boom, then the stack trace | stderr |
log.error('failed:', err) | error: failed: Error: boom, then the stack trace | stderr |
log.error(err.message) | error: boom | stderr |
log.warn(err) | warning: Error: boom, then the stack trace | stderr |
log.output(err) | Error: boom, then the stack trace | stdout |
log.output(err.message) | boom | stdout |
log.debug(err) | debug: Error: boom, then the stack trace | stdout |
Only error() omits its prefix, and only when the error is the first
argument, since the first line of the expanded error already starts with
its name (like Error: boom or TypeError: bad), which tells the
severity. This is deliberate. The other methods keep their prefix, since
without it a warning would look like an error, and a debug message like a
failure; and an error that is not the first argument of error() keeps the
prefix too. The methods without a prefix (always(), output(), info(),
and verbose()) expand an error in the same way, without one. It is the
same when the messages are buffered in the preliminary state.
A common pattern is to show the message at the error level, and the full
details only when the log level is debug or higher. It also works in the
preliminary state, since both messages are buffered and filtered when the
log level is set:
try {
// ...
} catch (err) {
// On stderr: `error: boom`.
log.error(err instanceof Error ? err.message : String(err))
// On stdout, only at `debug` or higher: `debug: Error: boom`,
// followed by the stack trace.
log.debug(err)
}
In TypeScript, the variable of a catch clause has the type unknown,
hence the instanceof check. To also keep the name of the error, use
String(err) instead of err.message: log.error(String(err)) outputs,
for example, error: TypeError: boom.
Timestamps
If the logger is created with the timestamp option, the messages of the
methods that have a prefix (error(), warn(), debug(), and trace())
start with a timestamp, and the prefix is replaced by the kind of the
message in square brackets:
const log = new Logger({ level: 'info', timestamp: true })
log.warn('the file is missing')
// 2026-11-11 23:32:31.358 [warning] the file is missing
Without the option, the same message is written as
warning: the file is missing.
The timestamp is in the local time, without the time zone, with
milliseconds, as YYYY-MM-DD HH:mm:ss.SSS. The kind is error, warning,
debug, or trace. The layout is the one of the logs of many editors and
tools:
2026-11-11 23:32:31.358 [error] Calculating the configuration failed.
Error: No configuration found.
at getConfig (/project/src/config.js:10:11)
The rules are:
- it is tied to the method, not to the prefix that is written:
error()with anErrorthat comes first has no prefix without the option (see Logging errors), but with the option it has the timestamp and the kind, as2026-11-11 23:32:31.358 [error] Error: boom, so all the stamped messages have the same structure; - the messages without a prefix (
always(),output(),info(), andverbose()) are the normal output and the progress messages, and are never stamped; - the timestamp and the kind are written on the first line only, like the
prefix, so the stack trace of an
Error, and the following lines of a multi-line message, are not stamped; - the time is taken when the message is logged, so the messages of the preliminary state keep it, although they are written later, when the log level is set;
- the local time has no time zone, so a log file does not say its own, and the hour is repeated when the clocks change;
- the option is fixed when the logger is created, and cannot be changed
later; the
timestampaccessor returns its value; - a value that is not a boolean is rejected with a
TypeError.
Empty messages
If the message is omitted or undefined, it is replaced by an empty
string, so log.info() and log.info(undefined) write an empty line, and
the methods with a prefix write only the prefix (for example debug: ).
This differs from console.log(), which writes undefined.
Other falsy values are written as they are (null, 0, and false give
null, 0, and false), and undefined is written as usual when it is
not the first argument (log.info('value:', undefined) gives
value: undefined). Since the empty string is still a message, any
further arguments are appended to it after a space (log.info(undefined, 1)
gives 1, with a leading space).
To write the text undefined, convert it explicitly:
log.info(String(value))
Logging untrusted input
The messages are written as they are, without any escaping, so text that comes from outside the application (like a file name, a user name, or the content of a network request) can forge messages, send control sequences to the terminal, and be interpreted as format directives:
- a newline in the text starts a new line in the output, and a prefix is
added only to the first line, so the text
'bob\nerror: forged'in awarn()call writes the linewarning: bob, followed by a line that looks like a genuineerror: forgedmessage; - control characters, like the ANSI escape sequences, are passed to the terminal unchanged;
- if the first argument contains directives (like
%s,%d, or%j) and there are further arguments, the directives consume them, solog.info(text, secret)may write the secret; a single argument is not processed (log.info('100%d')writes100%d), butlog.info('100%d', 5)writes1005.
Therefore pass the untrusted text as an argument, never as the first argument, with a constant format string:
log.info('user: %s', name)
This prevents the interpretation of the directives, but %s writes a
string as it is, including the newlines and the control characters. To also
escape them, use %j (JSON) or %O (as util.inspect()), which write the
string between quotes, with a newline as \n and the escape character as
\u001b or \x1B:
log.info('user: %j', name)
Note that %j calls the toJSON() method of an object, and that %j and
%O quote the strings.
Advanced topics
Delaying setting the log level
In some cases, the logger needs to be created very early in the application's lifecycle, even before the log level can be determined.
In such cases, if the logger is created without a log level, it is in a preliminary state. During this time, all messages are stored in an internal buffer. Once the log level is set, the buffer is replayed, and the messages are written, or discarded, according to the log level.
const log = new Logger()
log.trace('...') // Not shown immediately
log.level = 'trace' // Set level and show the buffered messages.
log.info('hello') // Displayed on stdout.
log.debug('world') // Ignored.
With the log level set, a message that is below the level is skipped
before it is formatted, which costs a few nanoseconds. In the preliminary
state the final log level is not known, so every message, including
debug() and trace(), is formatted immediately and stored in the
buffer, until the log level is set:
- the formatting is done even for the messages that are later discarded;
for example, an object passed to a
%odirective is inspected at each call (a few microseconds, against a fraction of a microsecond for a short string message); - the buffer is not limited, and a message of about 70 characters takes several hundred bytes, so a long running application that logs a lot before the log level is set should set it as early as possible;
- since the message is formatted when it is logged, a later change of an argument does not alter the buffered message.
The times and the sizes depend on the machine and on the Node.js version.
The checks of the log level (isDebugEnabled, isLevel(), and the others) are
true in the preliminary state, so the preparation of a message guarded by
them is done there too.
Nothing is written while the logger is in the preliminary state, not even
the messages of always() and error(). If the log level is never set
(for example when the application fails before it determines the level),
the buffered messages are never written and are lost. Set the log level on
every path, for example in a catch block, using hasLevel to check
whether it was set:
try {
// Determine the log level, then set it.
log.level = parseLevel(process.argv)
} catch (err) {
if (!log.hasLevel) {
log.level = Logger.recommendedLevel
}
log.error(err)
}
The buffer is emptied before the messages are written, so each buffered message is written at most once. If the console throws while the buffer is replayed, the exception is propagated from the level setter, the level remains set, and the buffered messages that were not yet written are discarded.
Extending the logger
A class can be derived from Logger, for example to redirect the messages,
to count them, or to change their format; to add a timestamp, use the
timestamp option of the constructor instead (see
Timestamps). The supported extension point is
the protected write() method: every message that passes the log level
check is formatted, prefixed, and passed to it, with the numeric level, the
function that writes the message (on the standard output or on the standard
error), and the message; an override can inspect, change, redirect, or drop
the message, and call super.write() to continue:
class UpperCaseLogger extends Logger {
protected override write(
numericLevel: NumericLogLevel,
loggerFunction: LoggerFunction,
message: string | undefined
): void {
super.write(numericLevel, loggerFunction, message?.toUpperCase())
}
}
In the preliminary state write() stores the message in the internal
buffer, and the function is called when the log level is set. A message
that is undefined is ignored.
The state of the logger is private. The protected members that gave a
subclass direct access to it (_console, levelNumericValue, levelName,
and buffer) are deprecated: they still work, with the same
behaviour, but they will be removed in the next major version; use the
public console, level, hasLevel, and isLevel() members instead (the
buffer has no replacement).