Winston 在 Nestjs 上使用 AWS Cloudwatch

Winston with AWS Cloudwatch on Nestjs

到目前为止我读过的所有文章和文档都在谈论 Cloudwatch 和 Winston 在 vanilla 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,但似乎找不到方法来做到这一点。

我正在使用预定义的传输层,但我是这样配置的:

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

我最近在 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。

编辑: 使用配置服务..

//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);
}