fiberprometheus icon indicating copy to clipboard operation
fiberprometheus copied to clipboard

Support for Examplar Metrics

Open kirankumar-grootan opened this issue 1 year ago • 1 comments

It should be a good to have support for examplar metrics

func (ps *FiberPrometheus) RegisterAt(app fiber.Router, url string, handlers ...fiber.Handler) {
	ps.defaultURL = url

	h := append(handlers, adaptor.HTTPHandler(promhttp.HandlerFor(ps.gatherer, promhttp.HandlerOpts{
		EnableOpenMetrics: true,
	})))
	app.Get(ps.defaultURL, h...)
}

func (ps *FiberPrometheus) Middleware(ctx *fiber.Ctx) error {
        ...

	// Update the request duration histogram
	elapsed := float64(time.Since(start).Nanoseconds()) / 1e9

        // Extract the trace ID from the user context to use it as an exemplar if available.
        traceID := trace.SpanContextFromContext(ctx.UserContext()).TraceID()

	// Retrieve the histogram metric for request duration, labeled with status code, method, and path.
	histogram := ps.requestDuration.WithLabelValues(statusCode, method, path)

	// Check if the trace ID is valid to potentially use it as an exemplar.
	if traceID.IsValid() {
	// If the histogram supports exemplars, record the observed duration with the trace ID as an exemplar.
		if histogramExemplar, ok := histogram.(prometheus.ExemplarObserver); ok {
			histogramExemplar.ObserveWithExemplar(elapsed, prometheus.Labels{"traceID": traceID.String()})
		}
	}

	// Record the observed duration in the histogram.
	histogram.Observe(elapsed)

	return err
}

IDK if there will be a performance hit on this. But it's working. Happy to hear better way of handling this

kirankumar-grootan avatar Jul 19 '24 09:07 kirankumar-grootan

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Sep 18 '24 02:09 github-actions[bot]

Not stale

kirankumar-grootan avatar Sep 25 '24 06:09 kirankumar-grootan

@kirankumar-grootan Doesn't this require also having opentelemetry as a dependency?

gaby avatar Oct 06 '24 22:10 gaby

yes @gaby "go.opentelemetry.io/otel/trace"

sry for not being active for long time

PR: https://github.com/ansrivas/fiberprometheus/pull/223

kirankumar-grootan avatar Nov 26 '24 19:11 kirankumar-grootan

yes @gaby "go.opentelemetry.io/otel/trace"

sry for not being active for long time

PR: #223

Left a comment in the PR

gaby avatar Jan 21 '25 15:01 gaby

@gaby when will this change be avaiable in public go pkg library as 2.9.0 release version?

kirankumar-grootan avatar Mar 03 '25 13:03 kirankumar-grootan

@kirankumar-grootan Just tagged the release. Thanks for the remainder.

https://github.com/ansrivas/fiberprometheus/releases/tag/v2.9.0

gaby avatar Mar 03 '25 13:03 gaby