Expose metric endpoint for prometheus

Hi,

I am trying to expose metrics for Prometheus but I could not find any resources about how to do this. Is there any documentation or example code?

Thanks.

Did you try SwiftPrometheus which is a backend for SwiftMetrics. I'm sure the author @MrLotU is also happy to help if you have questions/issues.

1 Like

I was looking into both. But I could not find any documentation about how to integrate it into Vapor. I wanted to measure response time per endpoint and expose it via /metrics endpoint but without any luck so far.

I see! @tanner0101 and @MrLotU any pointers on how to integrate with Vapor?

Vapor 4 uses swift-metrics by default. To add a /metrics endpoint you can add the following route:

    app.get("metrics") { req -> EventLoopFuture<String> in
        let promise = req.eventLoop.makePromise(of: String.self)
        try MetricsSystem.prometheus().collect(into: promise)
        return promise.futureResult
    }

This will return the prometheus metrics, given you have bootstrapped MetricsSystem with Prometheus like so:

let myProm = PrometheusClient()
MetricsSystem.bootstrap(myProm)

See also: GitHub - swift-server-community/SwiftPrometheus: Client side Prometheus library in Swift

1 Like

Vapor collects the follow metrics by default:

  • http_requests_total (counter)
  • http_request_errors_total (counter)
  • http_request_duration_seconds (timer)
1 Like

Thank you all. Now it works :)

Hi, sorry for a dumb question, but how would one access these?

Depends what you mean by "access" but generally the way to use metrics is to configure a specific backend for GitHub - apple/swift-metrics: A Metrics API for Swift (the readme lists a few), and then metrics emitted by any framework will show up in the backend of your choice.

For prometheus specifically, you'd use GitHub - swift-server-community/SwiftPrometheus: Client side Prometheus library in Swift

Ok great, thank you for the explanation! I thought that some of these are automatically available in Vapor without SwiftMetrics.