nestjs 引入 winstonjs 日志管理

216 阅读1分钟

winstaonjs

winstonjs 是一个日志库,用于管理日志的创建、存储等。

nestjs 集成

在 nestjs 中,只需要创建一个 WinstonLoggerService 就可以在该 Service 中对 winston 进行初始化配置,后续在使用时直接引入,也可以覆盖 nestjs 默认日志对象。

使用 winston-daily-rotate-file 插件 可以配置日志按天滚动存储,比如配置存储7天的日志,则之前的日志会被定时清除。确保日志文件不会占用太多存储空间。

import { Injectable, LoggerService } from '@nestjs/common';
import * as winston from 'winston';
import 'winston-daily-rotate-file';

@Injectable()
export class WinstonLoggerService implements LoggerService {
  private readonly logger: winston.Logger;

  constructor() {
    // 创建 Daily Rotate File transport
    const dailyRotateTransport = new winston.transports.DailyRotateFile({
      filename: './logs/%DATE%-app.log', // 日志文件名
      datePattern: 'YYYY-MM-DD', // 日志日期格式
      zippedArchive: true, // 启用日志文件压缩
      maxSize: '20m', // 每个日志文件最大大小
      maxFiles: '7d', // 保留日志文件7天
      level: 'info', // 设置最低日志级别
    });

    // 创建 Winston Logger
    this.logger = winston.createLogger({
      level: 'info', // 默认日志级别
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.timestamp(),
        winston.format.printf(
          ({ timestamp, level, message }) =>
            `${timestamp} [${level}]: ${message}`,
        ),
      ),
      transports: [
        dailyRotateTransport, // 添加 Daily Rotate File 传输
        new winston.transports.Console(), // 控制台输出
      ],
    });
  }

  log(message: string) {
    this.logger.info(message);
  }

  error(message: string, trace?: string) {
    this.logger.error(message, trace);
  }

  warn(message: string) {
    this.logger.warn(message);
  }

  debug(message: string) {
    this.logger.debug(message);
  }

  verbose(message: string) {
    this.logger.verbose(message);
  }
}