diff --git a/app/routers/metrics/endpoint.go b/app/routers/metrics/endpoint.go index 4d4b248..5ffee7d 100644 --- a/app/routers/metrics/endpoint.go +++ b/app/routers/metrics/endpoint.go @@ -17,7 +17,7 @@ func AddEndpointMetric (r *http.Request) (interface{}, int) { err = endpoints.AddEndpointMetric(body) if err != nil { - log.Printf(err.Error()) + log.Print(err.Error()) return nil, http.StatusInternalServerError } diff --git a/app/storage/clickhouse/client.go b/app/storage/clickhouse/client.go index b1319df..08fa1d1 100644 --- a/app/storage/clickhouse/client.go +++ b/app/storage/clickhouse/client.go @@ -3,6 +3,7 @@ package storage import ( "context" "fmt" + "log" "os" "github.com/ClickHouse/clickhouse-go/v2" @@ -20,6 +21,10 @@ func Connect() error { return nil } +func Close() { + Connection.Close() +} + func connect() (*driver.Conn, error) { var ( ctx = context.Background() @@ -45,4 +50,27 @@ func connect() (*driver.Conn, error) { return nil, err } return &conn, nil +} + +func Migrate() error { + rows, err := Connection.Query( + context.TODO(), + `CREATE TABLE IF NOT EXISTS endpoints ( + timestamp DateTime, + service_name LowCardinality(String), + endpoint LowCardinality(String), + status_code UInt16, + response_time_ms UInt32, + request_method LowCardinality(String), + ) + ENGINE = MergeTree + PARTITION BY toYYYYMM(timestamp) + ORDER BY (service_name, endpoint, request_method, timestamp)`, + ) + if err != nil { + log.Fatal(err) + return err + } + defer rows.Close() + return nil } \ No newline at end of file diff --git a/app/storage/clickhouse/tables/endpoints.go b/app/storage/clickhouse/tables/endpoints.go index 4aec007..01b800e 100644 --- a/app/storage/clickhouse/tables/endpoints.go +++ b/app/storage/clickhouse/tables/endpoints.go @@ -3,12 +3,13 @@ package storage import ( "context" client "monitoring/app/storage/clickhouse" + "time" "github.com/ClickHouse/clickhouse-go/v2/lib/driver" ) type EndpointMetric struct { - Timestamp int `json:"timestamp"` + Timestamp time.Time `json:"timestamp"` Service string `json:"service"` Endpoint string `json:"endpoint"` StatusCode int `json:"status_code"` diff --git a/main.go b/main.go index 877eca6..e5e7222 100644 --- a/main.go +++ b/main.go @@ -33,7 +33,8 @@ func main() { if err != nil { panic(err) } - + defer client.Close() + http.HandleFunc("/api/v1/metrics/endpoint", handlerWrapper(endpoint.AddEndpointMetric)) log.Printf("Server started") http.ListenAndServe(":1237", nil)