nest.js使用nest-winston日志一

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文件夹,要自定路径。

相关推荐
白雾茫茫丶10 天前
Nest.js 实战 (十二):优雅地使用事件发布/订阅模块 Event Emitter
nestjs·nest.js·发布订阅·event emitter
白雾茫茫丶15 天前
Nest.js 实战 (十一):配置热重载 HMR 给服务提提速
webpack·nest.js·hmr
白雾茫茫丶20 天前
Nest.js 实战 (十):使用 winston 打印和收集日志记录
nest.js·winston·nest-winston
白雾茫茫丶1 个月前
Nest.js 实战 (七):如何生成 SVG 图形验证码
svg·nest.js
白雾茫茫丶4 个月前
基于 React + Nest 全栈开发的后台系统
reactjs·nest.js·umi·ant-design
博丽七七5 个月前
Nest.js项目初始配置
开发语言·javascript·后端·typescript·ecmascript·nest.js
博丽七七5 个月前
Nest.js学习记录4
前端·javascript·后端·typescript·nest.js
博丽七七5 个月前
Nest.js学习记录3
前端·javascript·后端·typescript·node.js·nest.js
乐闻x8 个月前
实战篇:如何在 NestJS 项目中支持 i18n 国际化本地化
node.js·i18n·nest.js