首页
/ NestJS 执行时间监控装饰器实现方案

NestJS 执行时间监控装饰器实现方案

2025-04-29 04:16:17作者:江焘钦

在开发基于 NestJS 的分布式系统时,监控接口执行时间是一个常见的需求。当某些接口响应过慢时,我们需要快速定位性能瓶颈。本文将介绍如何在 NestJS 中实现一个优雅的执行时间监控方案。

核心思路

NestJS 的拦截器(Interceptor)机制非常适合用于实现执行时间监控。拦截器可以在方法执行前后插入自定义逻辑,这正是我们需要的。

实现方案

1. 创建时间监控拦截器

首先,我们创建一个可配置的拦截器,它能够:

  1. 记录方法开始执行的时间
  2. 在方法执行完成后计算耗时
  3. 当执行时间超过阈值时输出警告日志
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  constructor(private readonly threshold: number) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    const handlerName = context.getHandler().name;

    return next.handle().pipe(
      tap(() => {
        const executionTime = Date.now() - now;
        if (executionTime > this.threshold) {
          console.warn(
            `警告: ${handlerName} 方法执行时间 ${executionTime}ms 超过阈值 ${this.threshold}ms`
          );
        }
      }),
    );
  }
}

2. 创建装饰器工厂

为了使使用更加简洁,我们可以创建一个装饰器工厂函数:

import { UseInterceptors } from '@nestjs/common';

export const MaxExecutionTime = (threshold: number) => 
  UseInterceptors(new TimeoutInterceptor(threshold));

使用示例

在控制器中,我们可以这样使用这个装饰器:

import { Controller, Get } from '@nestjs/common';
import { MaxExecutionTime } from './timeout.decorator';

@Controller('example')
export class ExampleController {
  @Get()
  @MaxExecutionTime(500) // 设置500ms的阈值
  async getData() {
    // 这里是一些可能耗时的操作
    return { data: 'some data' };
  }
}

高级用法

1. 集成日志系统

我们可以将简单的 console.warn 替换为 NestJS 的 Logger 服务,实现更专业的日志记录:

import { Logger } from '@nestjs/common';

// 在拦截器中
const logger = new Logger('PerformanceMonitor');
logger.warn(
  `警告: ${handlerName} 方法执行时间 ${executionTime}ms 超过阈值 ${this.threshold}ms`
);

2. 添加性能指标收集

除了日志警告,我们还可以将性能数据收集起来,用于后续分析:

import { PrometheusService } from '../monitoring/prometheus.service';

// 在拦截器中
const metricsService = new PrometheusService();
metricsService.recordApiDuration(handlerName, executionTime);

注意事项

  1. 异步操作:拦截器已经正确处理了异步操作,包括 Promise 和 Observable
  2. 异常情况:如果方法抛出异常,拦截器仍然会计算执行时间
  3. 性能开销:虽然拦截器本身会引入少量性能开销,但在大多数情况下可以忽略不计

总结

通过自定义拦截器和装饰器,我们在 NestJS 中实现了一个灵活的执行时间监控方案。这种实现方式具有以下优点:

  1. 非侵入性:不需要修改业务逻辑代码
  2. 可配置性:可以针对不同接口设置不同的阈值
  3. 可扩展性:可以轻松添加更多监控功能

这种模式不仅适用于执行时间监控,还可以应用于其他横切关注点,如日志记录、缓存、权限检查等,是 NestJS 中间件架构的一个典型应用场景。

登录后查看全文
热门项目推荐

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
178
262
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
866
513
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
183
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
265
305
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
note-gennote-gen
一款跨平台的 Markdown AI 笔记软件,致力于使用 AI 建立记录和写作的桥梁。
TSX
83
4
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
598
57
GitNextGitNext
基于可以运行在OpenHarmony的git,提供git客户端操作能力
ArkTS
10
3