33module Metrics
44 record MetricLabels , request_method : String , request_route : String , response_code : Int32
55
6- # Counts how many a given route was used
7- REQUEST_COUNTERS = Hash ( MetricLabels , Int64 ).new
8-
9- # Counts how much time was used to handle requests to each route
10- REQUEST_DURATION_SECONDS_SUMS = Hash (MetricLabels , Float32 ).new
6+ class RouteMetricsCollector < Kemal::Handler
7+ # Counts how many a given route was used
8+ @@num_of_request_counters = Hash ( MetricLabels , Int64 ).new
9+ # Counts how much time was used to handle requests to each route
10+ @@request_duration_seconds_sums = Hash (MetricLabels , Float32 ).new
1111
12- # The handler which will record metrics when registered in a Kemal application
13- METRICS_COLLECTOR = RouteMetricsCollector .new(REQUEST_COUNTERS , REQUEST_DURATION_SECONDS_SUMS )
12+ def self.num_of_request_counters
13+ return @@num_of_request_counters
14+ end
1415
15- class RouteMetricsCollector < Kemal::Handler
16- def initialize (
17- @num_of_request_counters : Hash (MetricLabels , Int64 ),
18- @request_duration_seconds_sums : Hash (MetricLabels , Float32 )
19- )
16+ def self.request_duration_seconds_sums
17+ return @@request_duration_seconds_sums
2018 end
2119
2220 def call (context : HTTP ::Server ::Context )
@@ -33,15 +31,15 @@ module Metrics
3331 LOGGER .trace(" Collecting metrics: handling #{ request_method } #{ request_path } took #{ seconds_spent_handling } s and finished with status #{ response_status } " )
3432 metric_key = MetricLabels .new request_path, request_method, response_status
3533
36- unless @num_of_request_counters .has_key?(metric_key)
37- @num_of_request_counters [metric_key] = 0
34+ unless @@ num_of_request_counters .has_key?(metric_key)
35+ @@ num_of_request_counters [metric_key] = 0
3836 end
39- @num_of_request_counters [metric_key] += 1
37+ @@ num_of_request_counters [metric_key] += 1
4038
41- unless @request_duration_seconds_sums .has_key?(metric_key)
42- @request_duration_seconds_sums [metric_key] = 0.0
39+ unless @@ request_duration_seconds_sums .has_key?(metric_key)
40+ @@ request_duration_seconds_sums [metric_key] = 0.0
4341 end
44- @request_duration_seconds_sums [metric_key] += seconds_spent_handling
42+ @@ request_duration_seconds_sums [metric_key] += seconds_spent_handling
4543 end
4644 end
4745 end
0 commit comments