monitoring/main.go
Egor Matveev 71d5fa2e25
All checks were successful
Deploy Dev / Build (pull_request) Successful in 59s
Deploy Dev / Push (pull_request) Successful in 37s
Deploy Dev / Deploy dev (pull_request) Successful in 15s
Deploy Prod / Build (pull_request) Successful in 58s
Deploy Prod / Push (pull_request) Successful in 39s
Deploy Prod / Deploy prod (pull_request) Successful in 15s
fix
2025-06-18 15:22:50 +03:00

70 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"log"
endpoint "monitoring/app/routers/metrics"
increment "monitoring/app/routers/metrics"
task "monitoring/app/routers/metrics"
client "monitoring/app/storage/clickhouse"
endpoints "monitoring/app/storage/clickhouse/tables"
"net/http"
"os"
"time"
)
func writeMetric(timestamp time.Time, endpoint string, statusCode int, responseTime int, method string) {
loc, _ := time.LoadLocation("Europe/Moscow")
err := endpoints.AddEndpointMetric(endpoints.EndpointMetric{
Timestamp: timestamp.In(loc),
Service: "monitoring",
Environment: os.Getenv("STAGE"),
Endpoint: endpoint,
StatusCode: statusCode,
ResponseTime: responseTime,
Method: method,
})
if err != nil {
log.Printf("Error sending metrics %s", err.Error())
}
}
func handlerWrapper(f func(*http.Request) (interface{}, int)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
response, status := f(r)
if response != nil {
data, err := json.Marshal(response)
if err != nil {
log.Printf("Error marshalling response")
status = http.StatusInternalServerError
}
w.WriteHeader(status)
w.Write(data)
} else {
w.WriteHeader(status)
}
go writeMetric(start, r.URL.Path, status, int(time.Since(start).Milliseconds()), r.Method)
log.Printf("%s %d %s", r.URL, status, time.Since(start))
}
}
func main() {
err := client.Connect()
if err != nil {
panic(err)
}
defer client.Close()
err = client.Migrate()
if err != nil {
panic(err)
}
http.HandleFunc("/api/v1/metrics/endpoint", handlerWrapper(endpoint.AddEndpointMetric))
http.HandleFunc("/api/v1/metrics/task", handlerWrapper(task.AddTaskMetric))
http.HandleFunc("/api/v1/metrics/increment", handlerWrapper(increment.AddIncrementMetric))
log.Printf("Server started")
http.ListenAndServe(":1237", nil)
}