How to use the xPack Logger
This section is intended for those who plan to use this module in their own projects.
The @xpack/logger
module can be imported into both TypeScript
and JavaScript Node.js code.
In TypeScript and ECMAScript modules, use import
:
import { Logger } from '@xpack/logger'
In JavaScript with CommonJS, use require()
:
const { Logger } = request('@xpack/logger')
The module can be included in any application and 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:
const log = new Logger({
level: 'info'
})
log.info('hello') // Displayed on stdout.
log.debug('world') // Ignored.
In more complex use cases, the log level can be tested and the (possibly) long operations be performed only if necessary.
Log levels
The following strings are recognised as valid level names:
export type LogLevel =
'silent' | 'error' | 'warn' | 'info' | 'verbose' | 'debug' | 'trace' | 'all'
Internally, string levels are converted to integer values for comparison purposes. Higher integer values correspond to greater verbosity.
Delaying setting the log level
In some cases, the logger needs to be initialized very early in the application's lifecycle, even before the log level can be determined.
In such cases, if the logger is initialized without a specified log level, it enters a preliminary state. During this time, all log entries are stored in an internal buffer. Once the log level is set, the buffer is processed, and the log entries are handled accordingly.
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.
Output methods
The following methods are available to log messages:
always (message: any = '', ...args: any[]): void
error (message: any = '', ...args: any[]): void
error (message: Error): void
output (message: any = '', ...args: any[]): void
warn (message: any = '', ...args: any[]): void
info (message: any = '', ...args: any[]): void
verbose (message: any = '', ...args: any[]): void
debug (message: any = '', ...args: any[]): void
trace (message: any = '', ...args: any[]): void
Log level checks
When preparing the log messages is expensive, it makes no sense to do it and call the output method to simply return if the log level is low and the message is not needed.
Instead, the log level can be checked explicitly:
if (log.isDebug) {
const message = invoke_long_method()
log.debug(message)
}
Reference
For more details on the available class definitions, including all methods, accessors, properties, etc, please see the TypeDoc API Reference pages.