diff --git a/echoprometheus/prometheus.go b/echoprometheus/prometheus.go index cc864c8..1f9ed82 100644 --- a/echoprometheus/prometheus.go +++ b/echoprometheus/prometheus.go @@ -11,17 +11,19 @@ import ( "context" "errors" "fmt" + "io" + "net/http" + "sort" + "strconv" + "strings" + "time" + "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/labstack/gommon/log" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/expfmt" - "io" - "net/http" - "sort" - "strconv" - "time" ) const ( @@ -273,10 +275,17 @@ func (conf MiddlewareConfig) ToMiddleware() (echo.MiddlewareFunc, error) { values[2] = c.Request().Host values[3] = url for _, cv := range customValuers { - values[cv.index] = cv.valueFunc(c, err) + values[cv.index] = strings.ToValidUTF8(cv.valueFunc(c, err), "�") } - requestDuration.WithLabelValues(values...).Observe(elapsed) + // The first metric set is done this way to ensure + // that the values all contain valid UTF8. If not, it + // returns, if they are then .WithLabelValues is fine. + if obs, tmpErr := requestDuration.GetMetricWithLabelValues(values...); tmpErr == nil { + obs.Observe(elapsed) + } else { + return fmt.Errorf("requestDuration observation failed, err: %w", tmpErr) + } requestCount.WithLabelValues(values...).Inc() requestSize.WithLabelValues(values...).Observe(float64(reqSz)) responseSize.WithLabelValues(values...).Observe(float64(c.Response().Size))