Custom loggers

To use your own logger with @node-ts/bus, create an adapter class by implementing the Logger interface. In this example winston is being used

import { Logger } from '@node-ts/bus-core'
import winston from 'winston'

export class WinstonLogger implements Logger {

  private winstonLogger: winston.Logger

  constructor (
    name: string // This is the name of the class the logger will be injected into
  ) {
    this.winstonLogger = winston.createLogger({
      format: winston.format.json(),
      defaultMeta: { name }
    })
  }

  debug (message: string, meta?: object): void {
    this.winstonLogger.debug(message, meta)
  }

  trace (message: string, meta?: object): void {
    this.winstonLogger.verbose(message, meta)
  }

  info (message: string, meta?: object): void {
    this.winstonLogger.info(message, meta)
  }

  warn (message: string, meta?: object): void {
    this.winstonLogger.warn(message, meta)
  }

  error (message: string, meta?: object): void {
    this.winstonLogger.error(message, meta)
  }

  fatal (message: string, meta?: object): void {
    this.winstonLogger.crit(message, meta)
  }
}

Configure @node-ts/bus-core to use your log adapter

import { Bus } from '@node-ts/bus-core'
import { WinstonLogger } from './winston-logger'
​
async function run () {
  const bus = await Bus.configure()
    .withLogger((target: string) => new WinstonLogger(target))
    .initialize()
}

Last updated