mirror of
https://github.com/casdoor/casdoor.git
synced 2025-07-03 12:30:19 +08:00
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:
@ -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()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user