【问题标题】:Winston with AWS Cloudwatch on NestjsWinston 在 Nestjs 上使用 AWS Cloudwatch
【发布时间】:2021-10-08 17:34:27
【问题描述】:

到目前为止,我阅读的所有文章和文档都谈到了 Cloudwatch 和 Winston 在一个普通 Node 应用程序上的集成,但没有关于 Nestjs 的内容

到目前为止,我的 app.module.ts 上有:

  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    MongooseModule.forRoot(
      `mongodb://${environment.MONGO_INITDB_ROOT_USERNAME}:${environment.MONGO_INITDB_ROOT_PASSWORD}@${environment.MONGODB_HOST}/${environment.MONGO_INITDB_DATABASE}`,
    ),
    VoucherModule,
    ApiKeyModule,
    WinstonModule.forRoot(loggerConfig),
  ],

其中 loggerConfig 是 Winston 的基本配置,具体取决于环境。

使用winston-cloudwatch 包我需要创建一个新的Transporter 并将其添加到winston,但似乎找不到这样做的方法。

【问题讨论】:

    标签: node.js amazon-web-services nestjs amazon-cloudwatch winston


    【解决方案1】:

    我最近在 Nestjs 中实现了 aws-cloudwatch 并遇到了类似的问题,但在浏览和阅读了有关 winston 和 cloudwatch 的一些信息后,我想出了这个解决方案。

    //main.ts
    import {
      utilities as nestWinstonModuleUtilities,
      WinstonModule,
    } from 'nest-winston';
    import * as winston from 'winston';
    import CloudWatchTransport from 'winston-cloudwatch';
    
    const app = await NestFactory.create(AppModule, {
      logger: WinstonModule.createLogger({
        format: winston.format.uncolorize(), //Uncolorize logs as weird character encoding appears when logs are colorized in cloudwatch.
        transports: [
          new winston.transports.Console({
            format: winston.format.combine(
              winston.format.timestamp(),
              winston.format.ms(),
              nestWinstonModuleUtilities.format.nestLike()
            ),
          }),
          new CloudWatchTransport({
            name: "Cloudwatch Logs",
            logGroupName: process.env.CLOUDWATCH_GROUP_NAME,
            logStreamName: process.env.CLOUDWATCH_STREAM_NAME,
            awsAccessKeyId: process.env.AWS_ACCESS_KEY,
            awsSecretKey: process.env.AWS_KEY_SECRET,
            awsRegion: process.env.CLOUDWATCH_AWS_REGION,
            messageFormatter: function (item) {
              return (
                item.level + ": " + item.message + " " + JSON.stringify(item.meta)
              );
            },
          }),
        ],
      }),
    });
    
    

    在这里,我们定义了两种传输方式,一种是 transports.Console(),它是默认的 winston 传输方式,另一种是 cloudwatch 传输方式。

    这基本上是替换默认的nestjs Logger(从@nestjs/common 导入)。所以,我们不必在任何模块中导入winston,甚至在“app.module.ts”中也不行。相反,只需在您需要的任何模块中导入 Logger,每当我们记录任何内容时,它都会显示在终端中并上传到 cloudwatch。

    编辑: 使用 configService..

    //main.js
    import {
      utilities as nestWinstonModuleUtilities,
      WinstonModule,
    } from 'nest-winston';
    import * as winston from 'winston';
    import CloudWatchTransport from 'winston-cloudwatch';
    import { ConfigService } from '@nestjs/config';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      const configService = app.get(ConfigService);
    
      app.useLogger(
        WinstonModule.createLogger({
          format: winston.format.uncolorize(),
          transports: [
            new winston.transports.Console({
              format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.ms(),
                nestWinstonModuleUtilities.format.nestLike(),
              ),
            }),
            new CloudWatchTransport({
              name: 'Cloudwatch Logs',
              logGroupName: configService.get('CLOUDWATCH_GROUP_NAME'),
              logStreamName: configService.get('CLOUDWATCH_STREAM_NAME'),
              awsAccessKeyId: configService.get('AWS_ACCESS_KEY'),
              awsSecretKey: configService.get('AWS_KEY_SECRET'),
              awsRegion: configService.get('CLOUDWATCH_AWS_REGION'),
              messageFormatter: function (item) {
                return (
                  item.level + ': ' + item.message + ' ' + JSON.stringify(item.meta)
                );
              },
            }),
          ],
        }),
      );
    
      await app.listen(configService.get('PORT') || 3000);
    }
    

    【讨论】:

    • 谢谢您,在这种情况下您将如何使用 configService 来获取环境变量?您的解决方案效果很好,但我宁愿创建一个配置文件来传递 createLogger 方法。
    • 我已经编辑了我的答案。这应该有效。
    • 感谢您的回答。我按照你的例子做了同样的事情 aliyun/alibaba clound 的 SLS 日志服务,相当于 aws 的 cloudwatch。我用这个包替换了 CloudWatchTransport:github.com/chylvina/winston-sls
    【解决方案2】:

    我正在使用预定义的传输层,但这就是我配置它的方式:

    const app = await NestFactory.create(AppModule);
    app.useLogger(
      WinstonModule.createLogger({
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.ms(),
          nestWinstonModuleUtilities.format.nestLike()
        ),
        transports: [new winston.transports.Console()]
      })
    );
    

    您无需将WinstonModule 导入任何模块(使用此解决方案)。

    有关所有 winston 日志记录选项,请参阅 https://www.npmjs.com/package/winston

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 2017-05-12
      • 2021-04-06
      相关资源
      最近更新 更多