Nest.JS LoggerService接口要使用Winston logger的实现,需要在使用者类中实例化实现

时间:2019-09-30 16:57:45

标签: node.js logging winston

我使用Nest.js并实现了LoggerService来定制记录器。在实现中,它使用Winston记录器,并且运行良好。


import { LoggerService } from '@nestjs/common';
import * as winston from 'winston';
import { config } from '../config';
import * as path from 'path';
export class AppLogger implements LoggerService {
  private logger: winston.Logger;
  constructor(label?: string) {
    this.initializeLogger(label);
  }
  initializeLogger(label?: string) {
    this.logger = winston.createLogger({
      level: config.logger.level,
      format: winston.format.json(),
      transports: [
        new winston.transports.File({ dirname: path.join(__dirname, './../log/debug/'), filename: 'debug.log', level: 'debug' }),
        new winston.transports.File({ dirname: path.join(__dirname, './../log/error/'), filename: 'error.log', level: 'error' }),
        new winston.transports.File({ dirname: path.join(__dirname, './../log/info/'), filename: 'info.log', level: 'info' })
      ],
    });
    if (process.env.NODE_ENV !== 'production') {
      this.logger.add(
        new winston.transports.Console({
          format: winston.format.simple(),
        }),
      );
    }
  }
  error(message: string, trace: string) {
    this.logger.log("error", "MyLogger error - " + message);
    this.logger.error(message, trace);
  }

  warn(message: string) {
    this.logger.log("warn", "MyLogger error - " + message);
    //this.logger.warn('warn', message);
  }

  log(message: string) {
    this.logger.log("info", "MyLogger error - " + message);
    // this.logger.log('info', message);
  }

每个控制器,我都必须导入已实现的记录器,并在类级别实例化该记录器,以调用相应的log方法,如下所示。

import { Controller, Get } from '@nestjs/common';
import { config } from './../../config';
import { AppLogger } from '../app.logger'
@Controller()
export class HealthcheckController {
  private start: number;
  private logger: AppLogger = new AppLogger();
  constructor() {
    this.start = Date.now();
  }

  @Get('healthcheck')
  async get() {
    const now = Date.now();

    this.logger.error("This is from Healthcheck log","");
    return {
      status: 'pass',
      version: config.version,
      details: {
        uptime: `${Number((now - this.start) / 1000).toFixed(0)}`,
      },
    };
  }
}


在Main.ts

 this.app = await NestFactory.create<NestFastifyApplication>(
      AppModule,
      new FastifyAdapter({ logger: new AppLogger('Nest') }),
    );

请告知,如何避免在所有控制器上实例化记录器。

什么是最好的方法?

  private logger: AppLogger = new AppLogger();

1 个答案:

答案 0 :(得分:0)

使用依赖注入将服务通过构造函数注入到控制器中。

export class HealthcheckController {
...
public constructor(private readonly appLogger: AppLogger) {}

并且不要忘记在服务中使用@Injectable()装饰器

@Injectable()
export class AppLogger implements LoggerService {

Dependency injection fundamentals