winston日志

77 阅读1分钟

winston

npm install nest-winston winston winston-daily-rotate-file
npm install chalk:颜色标识

配置

// env
# winston-level
LOG_LEVEL="debug"
// config/winston.ts

import { ConfigService } from "@nestjs/config"
import chalk from "chalk";
import { WinstonModuleOptions } from "nest-winston";
import { format, transports } from "winston";
import "winston-daily-rotate-file";

export const winstonConfig = {
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => {
        // 日志输出的管道
        const transportsList: WinstonModuleOptions["transports"] = [
            new transports.DailyRotateFile({
                level: "error",
                dirname: `logs`,
                filename: `%DATE%-error.log`,
                datePattern: "YYYY-MM-DD",
                maxSize: "20m",
                format: format.combine(
                    // format.label({ label: 'right meow!' }),
                    format.timestamp({
                        format: 'YYYY-MM-DD HH:mm:ss', 
                    }),
                    format.printf(({ level, message, timestamp }) => {
                        return `${timestamp} ${level}: ${message}`;
                    })
                )
            }),
            new transports.DailyRotateFile({
                level: configService.get('LOG_LEVEL') || 'debug',
                dirname: `logs`,
                filename: `%DATE%-combined.log`,
                datePattern: "YYYY-MM-DD",
                maxSize: "20m",
                format: format.combine(
                    format.timestamp({
                        format: 'YYYY-MM-DD HH:mm:ss', 
                    }),
                    format((info) => {
                        if (info.level === "error") {
                            return false; // 过滤掉'error'级别的日志
                        }
                        return info;
                    })(),
                    format.printf(({ level, message, timestamp }) => {
                        return `${timestamp} ${level}: ${message}`;
                    })
                )
            })
        ];
        // 开发环境下,输出到控制台
        if (process.env.NODE_ENV === "development") {
            transportsList.push(new transports.Console(
                {
                    level: configService.get('LOG_LEVEL') || 'debug',
                    format: format.combine(
                        format.colorize(),
                        format.timestamp({
                            format: 'YYYY-MM-DD HH:mm:ss', 
                        }),
                        format.printf(({ level, message, timestamp }) => {
                            const appStr = chalk.green(`[WINSTON]`);
                            return `${appStr} ${timestamp} ${level} ${message} `;
                        })
                    ),

                }
            ));
        }

        return {
            transports: transportsList
        };
    }
}

// const levels = {error: 0,warn: 1, info: 2,http: 3,verbose: 4,debug: 5,silly: 6};
// 当我们配置level为wran的时候,它会记录小于或等于当前等级的日志信息
// app.module.ts

@Module({
  imports: [
    // 配置项
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV || 'development'}`,
    }),

    // 日志
    WinstonModule.forRootAsync(winstonConfig),

打印日志

export class HttpExceptionFilter implements ExceptionFilter {
    constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) { }

      // 记录日志      
    this.logger.error(message);