Skip to content

Provides a NestJS LoggerModule and decorators for use with @tgarif/logger.

License

Notifications You must be signed in to change notification settings

tgarif/node-logger-nestjs

Repository files navigation

@tgarif/logger-nestjs

npm

Installation

npm i @tgarif/logger-nestjs

Usage

import { Module, Injectable, Inject } from '@nestjs/common';
import { createLogger, LogService } from '@tgarif/logger';
import { LoggerModule, LOGGER } from '@tgarif/logger-nestjs';

const logger = createLogger('app');

@Module({
  imports: [LoggerModule.forRoot(logger)],
  providers: [HelperService],
})
export class AppModule {}

@Injectable()
class HelperService {
  constructor(@Inject(LOGGER) private log: LogService) {}

  logFoo() {
    this.log.info('foo');
  }

  logChild() {
    this.log.createLogger('childLogger').info('child foo');
  }
}

The @InjectLogger() Decorator

As a preferred alternative, a child logger can be injected directly, without having to inject the root log service to create a logger in a second step.

The @InjectLogger() decorator takes a namespace string as argument.

If no argument is passed, the root LogService is returned.

import { Module, Injectable, Inject } from '@nestjs/common';
import { createLogger, LogService } from '@tgarif/logger';
import { LoggerModule, InjectLogger } from '@tgarif/logger-nestjs';

const logger = createLogger('app');

@Module({
  imports: [LoggerModule.forRoot(logger)],
  providers: [HelperService],
})
export class AppModule {}

@Injectable()
class HelperService {
  constructor(
    @InjectLogger('helper') private log: LogService,
    @InjectLogger() private rootLog: LogService,
  ) {}

  logFoo() {
    // This will output "INFO [app:helper] foo"
    this.log.info('foo');
  }

  logRootFoo() {
    // This will output "INFO [app] foo"
    this.rootLog.info('foo');
  }

  logChild() {
    // This will NOT work here, our logger is already a child logger.
    // this.log.createLogger('childLogger').info('child foo');
  }
}

License

MIT License © 2023-PRESENT Tengku Arif

About

Provides a NestJS LoggerModule and decorators for use with @tgarif/logger.

Resources

License

Stars

Watchers

Forks

Packages

No packages published