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

相关推荐
weixin_431600447 小时前
NestJS 入门(7):生命周期钩子——构造函数和 `OnModuleInit` 差在哪?
前端·后端·学习·node.js·nest.js
weixin_431600444 天前
NestJS 入门(3):Guard 如何挡住未登录请求?
前端·后端·学习·nest.js
weixin_431600444 天前
前端对接 SSE 的两种常见方式
前端·后端·学习·ai·sse·nest.js
weixin_431600445 天前
NestJS 入门(1):先搞懂 Module、Controller、Service
开发语言·前端·后端·nest.js
贩卖黄昏的熊14 天前
NestJS简明教程——安全
开发语言·javascript·安全·typescript·nest.js
贩卖黄昏的熊14 天前
NestJS简明教程——异常处理和日志
javascript·node.js·nest.js
qq_283720055 个月前
nestjs实战(五):从零搭建NestJS+TypeORM+原生驱动+达梦DM8,两种连接融合
达梦·orm·nest.js·dm·原生
qq_283720055 个月前
nestjs实战(六):诺依Nest.js + MySQL 项目改造为兼容达梦8数据库详细教程
javascript·数据库·mysql·达梦·nest.js·诺依
xiaoxue..7 个月前
Nest.js 框架 企业级开发通关手册
面试·typescript·node.js·开发框架·nest.js
亮子AI10 个月前
【NestJS】在 nest.js 项目中,如何使用 Postgresql 来做缓存?
开发语言·缓存·node.js·nest.js