Skip to content

Custom Logger

Xeno.JS lets you add your own logging provider by implementing ILoggerClient.

Implement ILoggerClient and its track() method:

import type { ILoggerClient, LogLevel } from '@xeno-js/shared'
class MyLogger implements ILoggerClient {
track<T>(
level: LogLevel,
message: string,
context: T | undefined,
error: unknown | undefined,
): void {
console.log({
level,
message,
context,
error,
})
}
}

The track() method receives the log level, message, optional logging context, and optional error.

Pass a factory through customLoggers:

import { XenoAppBuilder } from '@xeno-js/core'
const app = new XenoAppBuilder()
app.addLogger((options) => {
options.customLoggers = [
() => new MyLogger(),
]
})

Provide a factory that returns an ILoggerClient:

options.customLoggers = [
() => new MyLogger(),
]

The logger module processes the registered factory during application build. The shown contract does not pass a service scope or container to the factory.

After building the application, resolve TOKENS.LOGGER:

import { XenoAppBuilder } from '@xeno-js/core'
import { TOKENS } from '@xeno-js/shared'
const app = new XenoAppBuilder()
app.addLogger((options) => {
options.customLoggers = [
() => new MyLogger(),
]
})
await app.build()
const { logger } = app.getServices()
logger.info('Application started')
logger.error('Something went wrong', new Error('Example error'))

TOKENS.LOGGER resolves the Xeno.JS application logger. Your custom logger is registered as one of its logging clients, so it receives the log events together with any other configured providers.

import { XenoAppBuilder } from '@xeno-js/core'
import { TOKENS } from '@xeno-js/shared'
import type { ILoggerClient, LogLevel } from '@xeno-js/shared'
class MyLogger implements ILoggerClient {
track<T>(
level: LogLevel,
message: string,
context: T | undefined,
error: unknown | undefined,
): void {
console.log({
level,
message,
context,
error,
})
}
}
const app = new XenoAppBuilder()
app.addLogger((options) => {
options.customLoggers = [
() => new MyLogger(),
]
})
await app.build()
const { logger } = app.getServices()
logger.info('Hello from Xeno.JS')

Related


Xeno.JS is an MIT-licensed open source project. It can grow thanks to the support of these awesome people. If you’d like to join them, please read more at support section