@tgarif/logger-nestjs
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

@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

Package Sidebar

Install

npm i @tgarif/logger-nestjs

Weekly Downloads

0

Version

0.2.0

License

MIT

Unpacked Size

20.7 kB

Total Files

13

Last publish

Collaborators

  • gorgc