Nest-Winston 项目教程
项目地址:https://gitcode.com/gh_mirrors/ne/nest-winston
项目介绍
Nest-Winston 是一个为 NestJS 框架设计的日志模块,它集成了流行的 Winston 日志库。Winston 是一个灵活且可扩展的日志库,支持多种日志级别和传输方式。Nest-Winston 通过提供一个 NestJS 模块包装器,使得在 NestJS 应用中使用 Winston 变得更加方便和高效。
项目快速启动
安装依赖
首先,你需要安装 Nest-Winston 和 Winston 库:
npm install --save nest-winston winston
配置 Nest-Winston
在你的 NestJS 应用的根模块(通常是 AppModule
)中导入并配置 WinstonModule
:
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
@Module({
imports: [
WinstonModule.forRoot({
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
),
}),
new winston.transports.File({
filename: 'logs/application.log',
format: winston.format.json(),
}),
],
}),
],
})
export class AppModule {}
使用日志服务
在你的服务或控制器中注入 WinstonLogger
并使用它来记录日志:
import { Controller, Inject } from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
@Controller('cats')
export class CatsController {
constructor(
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
) {}
@Get()
findAll() {
this.logger.info('Request to find all cats');
return [];
}
}
应用案例和最佳实践
日志级别管理
在生产环境中,你可能希望根据不同的日志级别将日志输出到不同的文件中。你可以通过配置不同的 transports
来实现这一点:
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
@Module({
imports: [
WinstonModule.forRoot({
transports: [
new winston.transports.Console({
level: 'info',
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
),
}),
new winston.transports.File({
level: 'error',
filename: 'logs/error.log',
format: winston.format.json(),
}),
new winston.transports.File({
level: 'info',
filename: 'logs/application.log',
format: winston.format.json(),
}),
],
}),
],
})
export class AppModule {}
日志轮转
为了防止日志文件过大,可以使用 winston-daily-rotate-file
插件来实现日志文件的自动轮转:
npm install --save winston-daily-rotate-file
然后在 WinstonModule
配置中添加 DailyRotateFile
传输:
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import * as DailyRotateFile from 'winston-daily-rotate-file';
@Module({
imports: [
WinstonModule.forRoot({
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
),
}),
new DailyRotateFile({
filename: 'logs/application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive:
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考