NestJS 使用 Winston 实现日志管理教程

NestJS 使用 Winston 实现日志管理教程

nest-winstonA Nest module wrapper form winston logger项目地址:https://gitcode.com/gh_mirrors/ne/nest-winston

1. 项目目录结构及介绍

.
├── src                           # 主要源代码目录
│   ├── app.module.ts            # 应用主模块,导入其他模块和配置
│   ├── main.ts                   # 应用入口文件,启动 NestJS 应用
│   └── services                  # 服务目录,包括自定义的服务类
│       └── logger.service.ts     # 自定义的日志服务
└── nest-cli.json                 # Nest CLI 配置文件
└── package.json                  # 项目依赖和脚本配置
└── README.md                     # 项目README
└── tsconfig.json                 # TypeScript 编译配置

在这个项目中,src/app.module.ts 是应用的核心模块,它导入并配置了必要的模块,包括 WinstonModulesrc/main.ts 是应用的启动文件,负责初始化 NestJS 应用。src/services/logger.service.ts 是一个示例的日志服务,展示了如何使用 nest-winston 集成 Winston 进行日志记录。

2. 项目的启动文件介绍 - main.ts

import { NestFactory } from '@nestjs/core';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';

import { AppModule } from './app.module';

// Winston 设置
const winstonConfig = {
  transports: [
    new winston.transports.File({ filename: 'combined.log', json: true }),
    new winston.transports.File({ filename: 'errors.log', level: 'error', json: true }),
  ],
};

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  // 配置 Winston
  app.useWinston(WinstonModule.createTransport(winstonConfig));

  await app.listen(3000);
}
bootstrap();

main.ts 文件中,我们通过 NestFactory.create() 初始化 NestJS 应用,然后使用 useWinston() 方法配置 Winston 模块,传递一个 winston 的配置对象,指定日志输出文件和级别。

3. 项目的配置文件介绍

虽然这个简单的例子没有特定的配置文件,但通常在实际项目中,你可能会将 Winston 配置放入单独的 JSON 或 TypeScript 文件中,以提高可维护性。例如:

config/logging.config.ts

export default {
  transports: [
    new winston.transports.File({ filename: 'combined.log', json: true }),
    new winston.transports.File({ filename: 'errors.log', level: 'error', json: true }),
  ],
};

然后在 main.ts 中导入并使用该配置:

import loggingConfig from './config/logging.config';

// ...

app.useWinston(WinstonModule.createTransport(loggingConfig));

这样可以让日志配置更加模块化,并方便在未来进行修改。

注意:在实际项目中,你可能还需要配置日志的级别、格式等更多细节,具体可以根据项目需求和 winston 的文档来进行调整。

nest-winstonA Nest module wrapper form winston logger项目地址:https://gitcode.com/gh_mirrors/ne/nest-winston

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时煜青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值