-
Notifications
You must be signed in to change notification settings - Fork 18
/
metrics.go
69 lines (59 loc) · 1.6 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* SPDX-License-Identifier: MIT
*/
package http
import (
"strings"
"time"
v1alpha2 "github.com/eclipse-symphony/symphony/coa/pkg/apis/v1alpha2"
observability "github.com/eclipse-symphony/symphony/coa/pkg/apis/v1alpha2/observability"
"github.com/eclipse-symphony/symphony/coa/pkg/apis/v1alpha2/utils"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
type Metrics struct {
Observability observability.Observability
}
func (m Metrics) Metrics(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
startTime := time.Now().UTC()
next(ctx)
endpoint := ctx.UserValue(router.MatchedRoutePathParam)
if endpoint != nil {
endpointString := utils.FormatAsString(endpoint)
if ctx.Response.StatusCode() >= 400 {
ApiOperationMetrics.ApiOperationErrors(
endpointString,
string(ctx.Method()),
formatErrorCode(ctx.Response.StatusCode()),
)
} else {
ApiOperationMetrics.ApiOperationLatency(
startTime,
endpointString,
string(ctx.Method()),
)
}
} else {
ApiOperationMetrics.ApiOperationErrors(
string(ctx.Path()),
string(ctx.Method()),
formatErrorCode(ctx.Response.StatusCode()),
)
}
}
}
// set the default errorcodes for the http request
func formatErrorCode(httpCode int) string {
errorCode := v1alpha2.State(httpCode).String()
if strings.HasPrefix(errorCode, "Unknown State:") {
if httpCode >= 400 && httpCode < 500 {
return "Bad Request"
} else {
return "Internal Error"
}
}
return errorCode
}