【问题标题】:How to get a classname along with logs in NestJS using Winston logger如何使用 Winston 记录器在 NestJS 中获取类名和日志
【发布时间】:2022-10-04 19:01:29
【问题描述】:

我使用 NestJS 作为后端服务,我想在其中添加一些记录器以获得更好的记录机制。虽然 NestJs 有一个默认记录器用于记录,但我在我的应用程序中使用 Winston。 我想要功能,所以我也可以在日志所属的日志中获得类名。

使用 NestJs 默认记录器,我可以在特定文件中使用以下代码来实现这一点

private readonly logger = new Logger(AppService.name);

通过使用上面的代码,我可以获得类名以及日志,即AppService

但是我在我的应用程序中使用了 nest-winston 包。我怎样才能得到同样的东西?

下面是我的代码:

import { Module } from '@nestjs/common';
import { WinstonModule,utilities as nestWinstonModuleUtilities } from 'nest-winston';
import * as winston from 'winston';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import * as path from 'path';

@Module({
imports: [ WinstonModule.forRoot({
          format: winston.format.combine(
                   winston.format.timestamp(),
                   winston.format.json(),
                   nestWinstonModuleUtilities.format.nestLike('MyApp', { prettyPrint: true }),
                  ),
          transports: [
                    new winston.transports.Console(),
                    new winston.transports.File({
                      dirname: path.join(__dirname, '../log/info/'), //path to where save logging result 
                      filename: 'info.txt', //name of file where will be saved logging result
                      level: 'info',
                    }),
                  ],        
       }),],
 controllers: [AppController],
 providers: [AppService],
})
export class AppModule {}

我需要改变什么?

【问题讨论】:

    标签: logging nestjs nest-winston


    【解决方案1】:

    nest-winston 中的 Logger 类的行为与预构建的 Nest 记录器不同。您必须在每次调用 log(), debug(), error() and verbose() 方法时传递服务名称。

    基于documentation,这是您在将其替换为nest Logger 后如何使用winston 记录器服务的方式。

    import { Controller, Get, Logger } from '@nestjs/common';
    import { AppService } from './app.service';
    
    @Controller()
    export class AppController {
      constructor(
        private readonly appService: AppService,
        private readonly logger: Logger,
      ) {}
    
      @Get()
      getHello(): string {
        this.logger.log('Calling getHello()', AppController.name);
        this.logger.debug('Calling getHello()', AppController.name);
        this.logger.verbose('Calling getHello()', AppController.name);
        this.logger.warn('Calling getHello()', AppController.name);
    
        try {
          throw new Error()
        } catch (e) {
          this.logger.error('Calling getHello()', e.stack, AppController.name);
        }
    
        return this.appService.getHello();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2015-04-15
      • 2021-07-16
      • 1970-01-01
      • 2014-12-03
      相关资源
      最近更新 更多