原创

如何在 Java/Spark 应用程序中使用 Micrometer 和 Prometheus 捕获 HTTP 响应状态代码?

温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

I'm working on a Java project using Spark, Micrometer, and Prometheus for monitoring. I've successfully implemented metrics for endpoint call counts and response times. However, I'm struggling to capture the HTTP response status codes (200, 400, 500, etc.).

I've tried using Counters with tags to store the status code as a value, but I haven't been able to get Micrometer to register them. Here's my relevant code snippet (other counters and endpoints omitted for brevity):

public class MiAplicacion {

  static PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

  static Counter peticionesPorEstadoCounter = Counter.builder("http.requests")
      .tag("method", "GET")
      .tag("path", "/tipoRespuesta")
      .register(registry);

  public static void main(String[] args) {
    Spark.port(8080);
    Spark.get("/metrics", (req, res) -> registry.scrape());
    Spark.get("/tipoRespuesta", (req, res) -> {
      int estadoRespuesta = tipoRespuesta();
      res.status(estadoRespuesta);
      peticionesPorEstadoCounter.increment(); // Track counter here
      return res;
    });
  }

  public static int tipoRespuesta() {
    Random random = new Random();
    int randomNumber = random.nextInt(3) + 1;
    int estadoRespuesta;
    switch (randomNumber) {
      case 1:
        estadoRespuesta = 200;
        break;
      case 2:
        estadoRespuesta = 400;
        break;
      default:
        estadoRespuesta = 500;
    }
    return estadoRespuesta;
  }
}

Here's my project's POM for reference:

<dependencies>
  <dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-core</artifactId>
    <version>1.8.0</version>
  </dependency>
  <dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.8.0</version>
  </dependency>

  <dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.9.3</version>
  </dependency>
</dependencies>

Any suggestions on how to effectively capture HTTP response status codes and register them as metrics in this scenario?

正文到此结束
热门推荐
本文目录