mirror of
https://github.com/casdoor/casdoor.git
synced 2025-07-03 12:30:19 +08:00
feat: support for prometheus (#1784)
This commit is contained in:
51
routers/prometheus_filter.go
Normal file
51
routers/prometheus_filter.go
Normal file
@ -0,0 +1,51 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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)
|
||||
}
|
||||
object.MemoryUsage.WithLabelValues("memoryUsed").Set(float64(systemInfo.MemoryUsed))
|
||||
object.MemoryUsage.WithLabelValues("memoryTotal").Set(float64(systemInfo.MemoryTotal))
|
||||
}
|
@ -21,8 +21,8 @@ package routers
|
||||
|
||||
import (
|
||||
"github.com/beego/beego"
|
||||
|
||||
"github.com/casdoor/casdoor/controllers"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@ -239,4 +239,7 @@ func initAPI() {
|
||||
|
||||
beego.Router("/api/get-system-info", &controllers.ApiController{}, "GET:GetSystemInfo")
|
||||
beego.Router("/api/get-version-info", &controllers.ApiController{}, "GET:GetVersionInfo")
|
||||
beego.Router("/api/get-prometheus-info", &controllers.ApiController{}, "GET:GetPrometheusInfo")
|
||||
|
||||
beego.Handler("/api/metrics", promhttp.Handler())
|
||||
}
|
||||
|
Reference in New Issue
Block a user