feat: fix prometheus filter bugs (#1792)

* fix: fix prometheus

* fix: count latency with prefix api

* fix: latency should not be counted when startTime is nil
This commit is contained in:
OutOfEastGate
2023-04-26 22:18:48 +08:00
committed by GitHub
parent 4c1915b014
commit e4c36d407f
5 changed files with 40 additions and 42 deletions

View File

@ -2,46 +2,14 @@ package routers
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/beego/beego/context"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
type PrometheusMiddleWareWrapper struct {
handler http.Handler
}
func PrometheusMiddleWare(h http.Handler) http.Handler {
return &PrometheusMiddleWareWrapper{
handler: h,
}
}
func (p PrometheusMiddleWareWrapper) ServeHTTP(w http.ResponseWriter, req *http.Request) {
method := req.Method
endpoint := req.URL.Path
if strings.HasPrefix(endpoint, "/api/metrics") {
systemInfo, err := util.GetSystemInfo()
if err == nil {
recordSystemInfo(systemInfo)
}
p.handler.ServeHTTP(w, req)
return
}
if strings.HasPrefix(endpoint, "/api") {
start := time.Now()
p.handler.ServeHTTP(w, req)
latency := time.Since(start).Milliseconds()
object.TotalThroughput.Inc()
object.APILatency.WithLabelValues(endpoint, method).Observe(float64(latency))
object.APIThroughput.WithLabelValues(endpoint, method).Inc()
}
}
func recordSystemInfo(systemInfo *util.SystemInfo) {
for i, value := range systemInfo.CpuUsage {
object.CpuUsage.WithLabelValues(fmt.Sprintf("%d", i)).Set(value)
@ -49,3 +17,21 @@ func recordSystemInfo(systemInfo *util.SystemInfo) {
object.MemoryUsage.WithLabelValues("memoryUsed").Set(float64(systemInfo.MemoryUsed))
object.MemoryUsage.WithLabelValues("memoryTotal").Set(float64(systemInfo.MemoryTotal))
}
func PrometheusFilter(ctx *context.Context) {
method := ctx.Input.Method()
path := ctx.Input.URL()
if strings.HasPrefix(path, "/api/metrics") {
systemInfo, err := util.GetSystemInfo()
if err == nil {
recordSystemInfo(systemInfo)
}
return
}
if strings.HasPrefix(path, "/api") {
ctx.Input.SetData("startTime", time.Now())
object.TotalThroughput.Inc()
object.ApiThroughput.WithLabelValues(path, method).Inc()
}
}