当前位置: 首页 > news >正文

nest.js使用nest-winston日志一

nest-winston文档

nest-winston - npm

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

安装

cnpm install --save nest-winston winstoncnpm 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文件夹,要自定路径。

http://www.lryc.cn/news/309498.html

相关文章:

  • LeetCode刷题笔记之二叉树(四)
  • 【MATLAB源码-第150期】基于matlab的开普勒优化算法(KOA)机器人栅格路径规划,输出做短路径图和适应度曲线。
  • 最佳实践:Websocket 长连接状态如何保持
  • Unity AStar寻路算法与导航
  • JavaScript最新实现城市级联操作,json格式的数据
  • SD NAND:为车载显示器注入智能与安全的心脏
  • 矩阵的对角化
  • React编写组件时,如何省略.tsx后缀
  • 移动端的React项目中如何配置自适应和px转rem
  • TypeScript 结合 React 开发时候 , React.FunctionComponent 解释
  • 2280. 最优标号(最小割,位运算)#困难,想不到
  • RestTemplate启动问题解决
  • Docker部署前后端服务示例
  • 方格分割644--2017蓝桥杯
  • 接口测试用例设计注意点
  • 学习linux从0到工程师(命令)-4
  • 【树莓派系统配置+python3.8+环境配置踩坑点汇总】raspberrypi
  • CTFHUB--文件包含漏洞--RCE
  • Android 解决引入的三方库中类名冲突问题
  • 扩展学习|大数据分析的现状和分类
  • java学习笔记-初级
  • 使用axios 封装大文件上传,支持断点续传的功能
  • 在python中,设置json支持中文字符串
  • qnx du统计目录大小单位
  • 测试人员如何向开发人员准确清晰地描述问题?
  • 何恺明新作 l-DAE:解构扩散模型
  • 【数学建模获奖经验】2023第八届数维杯数学建模:华中科技大学本科组创新奖获奖分享
  • Kubernetes(k8s第二部分)
  • mac新环境
  • 神经网络基础知识:LeNet的搭建-训练-预测