support metrics sending via grpc
This commit is contained in:
@ -16,7 +16,8 @@ import (
|
||||
"github.com/gorilla/mux"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.25.0"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
@ -57,6 +58,7 @@ func setupHTTP(cfg config.HTTP, srv xhttp.Server, log *slog.Logger) *http.Server
|
||||
mux.CORSMethodMiddleware(router),
|
||||
middlewareLogger(log),
|
||||
middlewareTrace(),
|
||||
middlewareMetrics(),
|
||||
)
|
||||
|
||||
setupCoursesHTTP(srv, router, log)
|
||||
@ -114,6 +116,53 @@ func (k attributeStringKey) Value(value string) attribute.KeyValue {
|
||||
return attribute.String(string(k), value)
|
||||
}
|
||||
|
||||
func must[T any](value T, err error) T {
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func middlewareMetrics() mux.MiddlewareFunc {
|
||||
requestDuration := must(webmetric.Float64Histogram(
|
||||
semconv.HTTPServerRequestDurationName,
|
||||
metric.WithUnit(semconv.HTTPServerRequestDurationUnit),
|
||||
metric.WithDescription(semconv.HTTPServerRequestDurationDescription),
|
||||
))
|
||||
|
||||
f := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
route := mux.CurrentRoute(r)
|
||||
hpath, _ := route.GetPathTemplate()
|
||||
|
||||
attributes := make([]attribute.KeyValue, 0, 8)
|
||||
attributes = append(
|
||||
attributes,
|
||||
semconv.HTTPRequestMethodOriginal(r.Method),
|
||||
semconv.URLFull(hpath),
|
||||
semconv.URLPath(r.URL.Path),
|
||||
)
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
if wr, ok := w.(*customResponseWriter); ok {
|
||||
statusCode := xdefault.WithFallback(wr.statusCode, http.StatusOK)
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPResponseStatusCode(statusCode),
|
||||
semconv.HTTPResponseBodySize(wr.wroteBytes),
|
||||
)
|
||||
}
|
||||
elapsed := time.Since(start).Truncate(time.Millisecond)
|
||||
requestDuration.Record(
|
||||
r.Context(), elapsed.Seconds(), metric.WithAttributes(attributes...))
|
||||
})
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func middlewareTrace() mux.MiddlewareFunc {
|
||||
reqidAttr := attributeStringKey("http.request_id")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user