java 在Spring Boot 中向http_server_requests_seconds_bucket指标添加自定义标签

6ovsh4lw  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(332)

我目前正在设计一款Spring Boot (Spring webflux)项目,在该项目中,我们在**/actuator/prometheus端点上公开了应用程序的指标。我们添加了 Spring Boot 执行器依赖项,默认情况下,它为我们提供了http_server_requests_seconds_bucket指标。默认情况下,它具有{exception=“None”,method=“POST”,outcome=“SUCCESS”,status=“200”,uri="/test”,le=“0.268435456”,}**标签。我想添加另一个标签,比如“challenge”,它取决于请求负载。例如,我的请求负载看起来像这样,

{
 "type" : "basic",
 "method" : "someMethod"
}

我想在该指标中添加一个标签,如http_server_requests_seconds_bucket{exception="None",method="POST",outcome="SUCCESS",status="200",uri="/pos/authenticate",le="0.268435456", challenge="basic"},它基于请求负载“type”参数。

**注意:**我们只允许有限数量的“type”值

1l5u6lss

1l5u6lss1#

如果你借用this solution中关于给现有prometheus执行器指标添加自定义标记的方法,并解析你感兴趣的属性的请求(我使用Jackson对象Map器),它应该能完成这个任务,看起来像下面这样:

@Bean
public WebMvcTagsContributor webMvcTagsContributor() {

    return new WebMvcTagsContributor() {
        @Override
        public Iterable<Tag> getTags(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Throwable exception
        ) {

            // parse the request body to get the property we're interested in later
            ObjectMapper mapper = new ObjectMapper();
            ThingToMapFromRequestBody bodyAsObject = null;
            try {
                bodyAsObject = mapper.readValue(request.getReader().lines().collect(Collectors.joining()),
                    ThingToMapFromRequestBody.class
                );
            } catch (IOException e) {
                e.printStackTrace();
            }

            // add the property we're interested in to our metrics
            Tags tags = Tags.empty();
            tags = tags.and(Tag.of("challenge", bodyAsObject != null ? bodyAsObject.type() : ""));
            return tags;
        }

        @Override
        public Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler) {

            return null;
        }
    };
}

// making use of a record rather than class, introduced in Java 14
record ThingToMapFromRequestBody(String type, String method) { }

相关问题