nest.js使用nest-winston日志一

时间:2024-03-09 07:37:15

nest-winston文档

nest-winston - npm

参考:nestjs中winston日志模块使用 - 浮的blog - SegmentFault 思否

安装

cnpm install --save nest-winston winston

cnpm install winston-daily-rotate-file

在main.ts中

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './common/response.interceptor'
import { HttpExceptionFilter } from './common/http-exception.filter';
import { createLogger } from 'winston';
import * as winston from 'winston';
import { WinstonModule, utilities, } from 'nest-winston'
import 'winston-daily-rotate-file';

async function bootstrap() {

  //日志
  const instance = createLogger({
    transports: [
      new winston.transports.Console({
        level: 'info',
        format: winston.format.combine(
          winston.format.timestamp(),
          utilities.format.nestLike()
        )
      }),
      new winston.transports.DailyRotateFile({
        level: 'error',
        dirname: 'logs',
        filename: 'error-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxSize: '10m',
        maxFiles: '14d',
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.simple(),
        ),
      }),
      new winston.transports.DailyRotateFile({
        level: 'info',
        dirname: 'logs',
        filename: 'info-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxSize: '10m',
        maxFiles: '14d',
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.simple(),
        ),
      }),
    ]
  })

  const logger = WinstonModule.createLogger({instance})
  
  const app = await NestFactory.create(AppModule, {
    logger
  });
  app.setGlobalPrefix('api');//路由前缀


  //全局响应拦截
  app.useGlobalInterceptors(new ResponseInterceptor());
  //全局异常拦截 只能有一个 写入日志
  app.useGlobalFilters(new HttpExceptionFilter(logger));

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

其中自定义异常 自动写入日志记录

app.useGlobalFilters(new HttpExceptionFilter(logger));
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, LoggerService } from '@nestjs/common';
import { Request, Response } from 'express';
/**
 * 封装 自定义 http 异常拦截
 */

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {

  //把错误异常自动加到日志
  constructor(
    private logger: LoggerService 
  ) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    // 请求和响应对象
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    // http状态码
    const status = exception.getStatus();

    this.logger.error(exception.message, exception.stack);
    let json = {
        code: status,
        msg: exception.message || exception.name, //exception.getResponse(),
        timestamp: new Date().toISOString(),
        path: request.url,
        method: request.method,
    }


    response.status(status).json(json);
  }
}

控制台打印结果

自动生成的logs文件夹

如果在生产环境,logs文件夹,要自定路径。