问题描述
到目前为止,我读到的所有文章和文档都谈到了Cloudwatch和Winston在Vanilla Node应用程序上的集成,但没有关于Nestjs的
到目前为止,我的app.mode.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包时,我需要创建一个新的传输器并将其添加到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)
);
},
}),
],
}),
});
在这里,我们定义了两个传输,一个是传输。控制台(),它是默认的Winston传输,另一个是CloudWatch传输。
这基本上是替换默认的nestjs Logger(从@nestjs/Common导入)。因此,我们不必在任何模块中导入Winston,即使是在‘app.mode.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);
}