Class: Tracekit::Middleware
- Inherits:
-
Object
- Object
- Tracekit::Middleware
- Defined in:
- lib/tracekit/middleware.rb
Overview
Rack middleware for automatic TraceKit instrumentation of HTTP requests Creates server spans with kind: :server for all incoming HTTP requests
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
7 8 9 10 |
# File 'lib/tracekit/middleware.rb', line 7 def initialize(app) @app = app @tracer = OpenTelemetry.tracer_provider.tracer('tracekit-ruby', Tracekit::VERSION) end |
Instance Method Details
#call(env) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/tracekit/middleware.rb', line 12 def call(env) sdk = SDK.current return @app.call(env) unless sdk request = Rack::Request.new(env) path = request.path method = request.request_method # Create server span for incoming HTTP request @tracer.in_span( span_name(request), attributes: span_attributes(request), kind: :server ) do |span| # Track metrics request_counter = sdk.counter("http.server.requests", { "http.method" => method, "http.route" => path }) active_gauge = sdk.gauge("http.server.active_requests", { "http.method" => method }) duration_histogram = sdk.histogram("http.server.request.duration", { "unit" => "ms" }) active_gauge.inc start_time = Time.now # Add client IP to span if client_ip = extract_client_ip(request) span.set_attribute("http.client_ip", client_ip) end begin status, headers, body = @app.call(env) # Set response attributes span.set_attribute("http.status_code", status) # Set span status based on HTTP status code if status >= 500 span.status = OpenTelemetry::Trace::Status.error("HTTP #{status}") elsif status >= 400 span.status = OpenTelemetry::Trace::Status.error("HTTP #{status}") else span.status = OpenTelemetry::Trace::Status.ok end # Record successful request request_counter.inc # Record errors if status >= 400 error_counter = sdk.counter("http.server.errors", { "http.method" => method, "http.status_code" => status.to_s }) error_counter.inc end [status, headers, body] rescue => e # Record exception on span span.record_exception(e) span.status = OpenTelemetry::Trace::Status.error("Exception: #{e.class.name}") # Record exception metric error_counter = sdk.counter("http.server.errors", { "http.method" => method, "error.type" => e.class.name }) error_counter.inc raise ensure active_gauge.dec duration = ((Time.now - start_time) * 1000).round(2) duration_histogram.record(duration) end end end |