如何优雅地自定义Prometheus监控指标

安全 应用安全
目前大部分使用Spring Boot构建微服务体系的公司,大都在使用Prometheus来构建微服务的度量指标(Metrics)类监控系统。而一般做法是通过在微服务应用中集成Prometheus指标采集SDK,从而使得Spring Boot暴露相关Metrics采集端点来实现。

[[389927]]

本文转载自微信公众号「无敌码农」,作者无敌码农。转载本文请联系无敌码农公众号。

大家好!我是"无敌码农",今天要和大家分享的是在实际工作中“如何优雅地自定义Prometheus监控指标”!目前大部分使用Spring Boot构建微服务体系的公司,大都在使用Prometheus来构建微服务的度量指标(Metrics)类监控系统。而一般做法是通过在微服务应用中集成Prometheus指标采集SDK,从而使得Spring Boot暴露相关Metrics采集端点来实现。

但一般来说,Spring Boot默认暴露的Metrics数量及类型是有限的,如果想要建立针对微服务应用更丰富的监控维度(例如TP90/TP99分位值指标之类),那么还需要我们在Spring Boot默认已经打开的Metrics基础之上,配置Prometheus类库(micrometer-registry-prometheus)所提供的其他指标类型。

但怎么样才能在Spring Boot框架中以更优雅地方式实现呢?难道需要在业务代码中编写各种自定义监控指标代码的暴露逻辑吗?接下来的内容我们将通过@注解+AOP的方式来演示如何以更加优雅的方式来实现Prometheus监控指标的自定义!

自定义监控指标配置注解

需要说明的是在Spring Boot应用中,对程序运行信息的收集(如指标、日志),比较常用的方法是通过Spring的AOP代理拦截来实现,但这种拦截程序运行过程的逻辑多少会损耗点系统性能,因此在自定义Prometheus监控指标的过程中,可以将是否上报指标的选择权交给开发人员,而从易用性角度来说,可以通过注解的方式实现。例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Tp { 
  13.  
  14.     String description() default ""

如上所示代码,我们定义了一个用于标注上报计时器指标类型的注解,如果想统计接口的想TP90、TP99这样的分位值指标,那么就可以通过该注解标注。除此之外,还可以定义上报其他指标类型的注解,例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Count { 
  13.  
  14.     String description() default ""

如上所示,我们定义了一个用于上报计数器类型指标的注解!如果要统计接口的平均响应时间、接口的请求量之类的指标,那么可以通过该注解标注!

而如果觉得分别定义不同指标类型的注解比较麻烦,对于某些接口上述各种指标类型都希望上报到Prometheus,那么也可以定义一个通用注解,用于同时上报多个指标类型,例如:

  1. package com.wudimanong.monitor.metrics.annotation; 
  2.  
  3. import java.lang.annotation.ElementType; 
  4. import java.lang.annotation.Inherited; 
  5. import java.lang.annotation.Retention; 
  6. import java.lang.annotation.RetentionPolicy; 
  7. import java.lang.annotation.Target; 
  8.  
  9. @Target({ElementType.METHOD}) 
  10. @Retention(RetentionPolicy.RUNTIME) 
  11. @Inherited 
  12. public @interface Monitor { 
  13.  
  14.     String description() default ""

总之,无论是分开定义特定指标注解还是定义一个通用的指标注解,其目标都是希望以更灵活的方式来扩展Spring Boot微服务应用的监控指标类型。

自定义监控指标注解AOP代理逻辑实现

上面我们灵活定义了上报不同指标类型的注解,而上述注解的具体实现逻辑,可以通过定义一个通用的AOP代理类来实现,具体实现代码如下:

  1. package com.wudimanong.monitor.metrics.aop; 
  2.  
  3. import com.wudimanong.monitor.metrics.Metrics; 
  4. import com.wudimanong.monitor.metrics.annotation.Count
  5. import com.wudimanong.monitor.metrics.annotation.Monitor; 
  6. import com.wudimanong.monitor.metrics.annotation.Tp; 
  7. import io.micrometer.core.instrument.Counter; 
  8. import io.micrometer.core.instrument.MeterRegistry; 
  9. import io.micrometer.core.instrument.Tag; 
  10. import io.micrometer.core.instrument.Tags; 
  11. import io.micrometer.core.instrument.Timer; 
  12. import java.lang.reflect.Method; 
  13. import java.util.function.Function
  14. import org.aspectj.lang.ProceedingJoinPoint; 
  15. import org.aspectj.lang.annotation.Around; 
  16. import org.aspectj.lang.annotation.Aspect; 
  17. import org.aspectj.lang.reflect.MethodSignature; 
  18. import org.springframework.stereotype.Component; 
  19.  
  20. @Aspect 
  21. @Component 
  22. public class MetricsAspect { 
  23.  
  24.     /** 
  25.      * Prometheus指标管理 
  26.      */ 
  27.     private MeterRegistry registry; 
  28.  
  29.     private Function<ProceedingJoinPoint, Iterable<Tag>> tagsBasedOnJoinPoint; 
  30.  
  31.     public MetricsAspect(MeterRegistry registry) { 
  32.         this.init(registry, pjp -> Tags 
  33.                 .of(new String[]{"class", pjp.getStaticPart().getSignature().getDeclaringTypeName(), "method"
  34.                         pjp.getStaticPart().getSignature().getName()})); 
  35.     } 
  36.  
  37.     public void init(MeterRegistry registry, Function<ProceedingJoinPoint, Iterable<Tag>> tagsBasedOnJoinPoint) { 
  38.         this.registry = registry; 
  39.         this.tagsBasedOnJoinPoint = tagsBasedOnJoinPoint; 
  40.     } 
  41.  
  42.     /** 
  43.      * 针对@Tp指标配置注解的逻辑实现 
  44.      */ 
  45.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Tp)"
  46.     public Object timedMethod(ProceedingJoinPoint pjp) throws Throwable { 
  47.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  48.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  49.         Tp tp = method.getAnnotation(Tp.class); 
  50.         Timer.Sample sample = Timer.start(this.registry); 
  51.         String exceptionClass = "none"
  52.         try { 
  53.             return pjp.proceed(); 
  54.         } catch (Exception ex) { 
  55.             exceptionClass = ex.getClass().getSimpleName(); 
  56.             throw ex; 
  57.         } finally { 
  58.             try { 
  59.                 String finalExceptionClass = exceptionClass; 
  60.                 //创建定义计数器,并设置指标的Tags信息(名称可以自定义) 
  61.                 Timer timer = Metrics.newTimer("tp.method.timed"
  62.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  63.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", tp.description()) 
  64.                                 .publishPercentileHistogram().register(this.registry)); 
  65.                 sample.stop(timer); 
  66.             } catch (Exception exception) { 
  67.             } 
  68.         } 
  69.     } 
  70.  
  71.     /** 
  72.      * 针对@Count指标配置注解的逻辑实现 
  73.      */ 
  74.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Count)"
  75.     public Object countMethod(ProceedingJoinPoint pjp) throws Throwable { 
  76.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  77.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  78.         Count count = method.getAnnotation(Count.class); 
  79.         String exceptionClass = "none"
  80.         try { 
  81.             return pjp.proceed(); 
  82.         } catch (Exception ex) { 
  83.             exceptionClass = ex.getClass().getSimpleName(); 
  84.             throw ex; 
  85.         } finally { 
  86.             try { 
  87.                 String finalExceptionClass = exceptionClass; 
  88.                 //创建定义计数器,并设置指标的Tags信息(名称可以自定义) 
  89.                 Counter counter = Metrics.newCounter("count.method.counted"
  90.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  91.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description"count.description()) 
  92.                                 .register(this.registry)); 
  93.                 counter.increment(); 
  94.             } catch (Exception exception) { 
  95.             } 
  96.         } 
  97.     } 
  98.  
  99.     /** 
  100.      * 针对@Monitor通用指标配置注解的逻辑实现 
  101.      */ 
  102.     @Around("@annotation(com.wudimanong.monitor.metrics.annotation.Monitor)"
  103.     public Object monitorMethod(ProceedingJoinPoint pjp) throws Throwable { 
  104.         Method method = ((MethodSignature) pjp.getSignature()).getMethod(); 
  105.         method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); 
  106.         Monitor monitor = method.getAnnotation(Monitor.class); 
  107.         String exceptionClass = "none"
  108.         try { 
  109.             return pjp.proceed(); 
  110.         } catch (Exception ex) { 
  111.             exceptionClass = ex.getClass().getSimpleName(); 
  112.             throw ex; 
  113.         } finally { 
  114.             try { 
  115.                 String finalExceptionClass = exceptionClass; 
  116.                 //计时器Metric 
  117.                 Timer timer = Metrics.newTimer("tp.method.timed"
  118.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  119.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", monitor.description()) 
  120.                                 .publishPercentileHistogram().register(this.registry)); 
  121.                 Timer.Sample sample = Timer.start(this.registry); 
  122.                 sample.stop(timer); 
  123.  
  124.                 //计数器Metric 
  125.                 Counter counter = Metrics.newCounter("count.method.counted"
  126.                         builder -> builder.tags(new String[]{"exception", finalExceptionClass}) 
  127.                                 .tags(this.tagsBasedOnJoinPoint.apply(pjp)).tag("description", monitor.description()) 
  128.                                 .register(this.registry)); 
  129.                 counter.increment(); 
  130.             } catch (Exception exception) { 
  131.             } 
  132.         } 
  133.     } 

上述代码完整的实现了前面我们定义的指标配置注解的逻辑,其中针对@Monitor注解的逻辑就是@Tp和@Count注解逻辑的整合。如果还需要定义其他指标类型,可以在此基础上继续扩展!

需要注意,在上述逻辑实现中对“Timer”及“Counter”等指标类型的构建这里并没有直接使用“micrometer-registry-prometheus”依赖包中的构建对象,而是通过自定义的Metrics.newTimer()这样的方式实现,其主要用意是希望以更简洁、灵活的方式去实现指标的上报,其代码定义如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.Counter; 
  4. import io.micrometer.core.instrument.Counter.Builder; 
  5. import io.micrometer.core.instrument.DistributionSummary; 
  6. import io.micrometer.core.instrument.Gauge; 
  7. import io.micrometer.core.instrument.MeterRegistry; 
  8. import io.micrometer.core.instrument.Timer; 
  9. import io.micrometer.core.lang.NonNull; 
  10. import java.util.function.Consumer; 
  11. import java.util.function.Supplier; 
  12. import org.springframework.beans.BeansException; 
  13. import org.springframework.context.ApplicationContext; 
  14. import org.springframework.context.ApplicationContextAware; 
  15.  
  16. public class Metrics implements ApplicationContextAware { 
  17.  
  18.     private static ApplicationContext context; 
  19.  
  20.     @Override 
  21.     public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { 
  22.         context = applicationContext; 
  23.     } 
  24.  
  25.     public static ApplicationContext getContext() { 
  26.         return context; 
  27.     } 
  28.  
  29.     public static Counter newCounter(String name, Consumer<Builder> consumer) { 
  30.         MeterRegistry meterRegistry = context.getBean(MeterRegistry.class); 
  31.         return new CounterBuilder(meterRegistry, name, consumer).build(); 
  32.     } 
  33.  
  34.     public static Timer newTimer(String name, Consumer<Timer.Builder> consumer) { 
  35.         return new TimerBuilder(context.getBean(MeterRegistry.class), name, consumer).build(); 
  36.     } 

上述代码通过接入Spring容器上下文,获取了MeterRegistry实例,并以此来构建像Counter、Timer这样的指标类型对象。而这里之所以将获取方法定义为静态的,主要是便于在业务代码中进行引用!

而在上述代码中涉及的CounterBuilder、TimerBuilder构造器代码定义分别如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.Counter; 
  4. import io.micrometer.core.instrument.Counter.Builder; 
  5. import io.micrometer.core.instrument.MeterRegistry; 
  6. import java.util.function.Consumer; 
  7.  
  8. public class CounterBuilder { 
  9.  
  10.     private final MeterRegistry meterRegistry; 
  11.  
  12.     private Counter.Builder builder; 
  13.  
  14.     private Consumer<Builder> consumer; 
  15.  
  16.     public CounterBuilder(MeterRegistry meterRegistry, String name, Consumer<Counter.Builder> consumer) { 
  17.         this.builder = Counter.builder(name); 
  18.         this.meterRegistry = meterRegistry; 
  19.         this.consumer = consumer; 
  20.     } 
  21.  
  22.     public Counter build() { 
  23.         consumer.accept(builder); 
  24.         return builder.register(meterRegistry); 
  25.     } 

上述代码为CounterBuilder构造器代码!TimerBuilder构造器代码如下:

  1. package com.wudimanong.monitor.metrics; 
  2.  
  3. import io.micrometer.core.instrument.MeterRegistry; 
  4. import io.micrometer.core.instrument.Timer; 
  5. import io.micrometer.core.instrument.Timer.Builder; 
  6. import java.util.function.Consumer; 
  7.  
  8. public class TimerBuilder { 
  9.  
  10.     private final MeterRegistry meterRegistry; 
  11.  
  12.     private Timer.Builder builder; 
  13.  
  14.     private Consumer<Builder> consumer; 
  15.  
  16.     public TimerBuilder(MeterRegistry meterRegistry, String name, Consumer<Timer.Builder> consumer) { 
  17.         this.builder = Timer.builder(name); 
  18.         this.meterRegistry = meterRegistry; 
  19.         this.consumer = consumer; 
  20.     } 
  21.  
  22.     public Timer build() { 
  23.         this.consumer.accept(builder); 
  24.         return builder.register(meterRegistry); 
  25.     } 

之所以还特地将构造器代码单独定义,主要是从代码的优雅性考虑!如果涉及其他指标类型的构造,也可以通过类似的方法进行扩展!

自定义指标注解配置类

在上述代码中我们已经定义了几个自定义指标注解及其实现逻辑代码,为了使其在Spring Boot环境中运行,还需要编写如下配置类,代码如下:

  1. package com.wudimanong.monitor.metrics.config; 
  2.  
  3. import com.wudimanong.monitor.metrics.Metrics; 
  4. import io.micrometer.core.instrument.MeterRegistry; 
  5. import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; 
  6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 
  7. import org.springframework.context.annotation.Bean; 
  8. import org.springframework.context.annotation.Configuration; 
  9. import org.springframework.core.env.Environment; 
  10.  
  11. @Configuration 
  12. public class CustomMetricsAutoConfiguration { 
  13.  
  14.     @Bean 
  15.     @ConditionalOnMissingBean 
  16.     public MeterRegistryCustomizer<MeterRegistry> meterRegistryCustomizer(Environment environment) { 
  17.         return registry -> { 
  18.             registry.config() 
  19.                     .commonTags("application", environment.getProperty("spring.application.name")); 
  20.         }; 
  21.     } 
  22.  
  23.     @Bean 
  24.     @ConditionalOnMissingBean 
  25.     public Metrics metrics() { 
  26.         return new Metrics(); 
  27.     } 

上述配置代码主要是约定了上报Prometheus指标信息中所携带的应用名称,并对自定义了Metrics类进行了Bean配置!

业务代码的使用方式及效果

接下来我们演示在业务代码中如果要上报Prometheus监控指标应该怎么写,具体如下:

  1. package com.wudimanong.monitor.controller; 
  2.  
  3. import com.wudimanong.monitor.metrics.annotation.Count
  4. import com.wudimanong.monitor.metrics.annotation.Monitor; 
  5. import com.wudimanong.monitor.metrics.annotation.Tp; 
  6. import com.wudimanong.monitor.service.MonitorService; 
  7. import org.springframework.beans.factory.annotation.Autowired; 
  8. import org.springframework.web.bind.annotation.GetMapping; 
  9. import org.springframework.web.bind.annotation.RequestMapping; 
  10. import org.springframework.web.bind.annotation.RequestParam; 
  11. import org.springframework.web.bind.annotation.RestController; 
  12.  
  13. @RestController 
  14. @RequestMapping("/monitor"
  15. public class MonitorController { 
  16.  
  17.     @Autowired 
  18.     private MonitorService monitorServiceImpl; 
  19.  
  20.     //监控指标注解使用 
  21.     //@Tp(description = "/monitor/test"
  22.     //@Count(description = "/monitor/test"
  23.     @Monitor(description = "/monitor/test"
  24.     @GetMapping("/test"
  25.     public String monitorTest(@RequestParam("name") String name) { 
  26.         monitorServiceImpl.monitorTest(name); 
  27.         return "监控示范工程测试接口返回->OK!"
  28.     } 

如上述代码所示,在实际的业务编程中就可以比较简单的通过注解来配置接口所上传的Prometheus监控指标了!此时在本地启动程序,可以通过访问微服务应用的“/actuator/prometheus”指标采集端点来查看相关指标,如下图所示:

有了这些自定义上报的监控指标,那么Promethues在采集后,我们就可以通过像Grafana这样的可视化工具,来构建起多维度界面友好地监控视图了,例如以TP90/TP99为例:

如上所示,在Grafana中可以同时定义多个PromeQL来定于不同的监控指标信息,这里我们分别通过Prometheus所提供的“histogram_quantile”函数统计了接口方法“monitorTest”的TP90及TP95分位值!而所使用的指标就是自定义的“tp_method_timed_xx”指标类型!

后记

以上就是我最近在工作中封装的一组关于Prometheus自定义监控指标的SDK代码,在实际工作中可以将其封住为Spring Boot Starter依赖的形式,从而更好地被Spring Boot项目集成!至此我已经毫无保留的将最近两天的工作成果分享给大家了,也希望各位老铁可以多多点赞支持,多多转发传播!

 

责任编辑:武晓燕 来源: 无敌码农
相关推荐

2023-12-29 08:01:52

自定义指标模板

2020-12-14 10:26:48

Prometheus 监控Services

2021-10-28 08:39:22

Node Export自定义 监控

2013-01-10 09:36:19

NagiosNagios插件

2023-03-26 08:41:37

2021-05-28 08:58:41

Golang网卡metrics

2022-07-08 08:00:31

Prometheus监控

2023-05-28 13:11:43

Plotly指标图表

2022-05-12 08:01:26

vmagentprometheus

2021-10-14 08:07:33

Go 应用Prometheus监控

2013-06-27 11:10:01

iOS开发自定义UISlider

2022-03-07 07:33:24

Spring自定义机制线程池

2023-09-06 08:46:47

2021-03-24 10:20:50

Fonts前端代码

2009-09-07 22:00:15

LINQ自定义

2010-02-07 14:02:16

Android 界面

2016-02-26 14:57:50

飞象网

2015-02-12 15:33:43

微信SDK

2011-04-06 15:05:58

nagios监控Linux

2009-09-03 13:34:03

.NET自定义控件
点赞
收藏

51CTO技术栈公众号