From d82fc1597f285b7bd5040f3a95425b70a0b5e845 Mon Sep 17 00:00:00 2001 From: Christian Gregg Date: Fri, 22 Mar 2024 13:36:08 +0000 Subject: [PATCH] feat: Propagate response attributes on Faraday::Error The current `Faraday` middleware won't report `http.status_code` in cases where an error is raised via another middleware (such as `:raise_error` or `:json`). This adds a special case for subclasses of `Faraday::Error` which have response information available, so that `http.status_code` the span status are still added to the span. --- .../faraday/middlewares/tracer_middleware.rb | 12 +++++++---- .../middlewares/tracer_middleware_test.rb | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/instrumentation/faraday/lib/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware.rb b/instrumentation/faraday/lib/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware.rb index 9289eacad..1b4452ac3 100644 --- a/instrumentation/faraday/lib/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware.rb +++ b/instrumentation/faraday/lib/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware.rb @@ -35,7 +35,11 @@ def call(env) ) do |span| OpenTelemetry.propagation.inject(env.request_headers) - app.call(env).on_complete { |resp| trace_response(span, resp) } + app.call(env).on_complete { |resp| trace_response(span, resp.status) } + rescue ::Faraday::Error => e + trace_response(span, e.response[:status]) if e.response + + raise end end @@ -62,9 +66,9 @@ def tracer Faraday::Instrumentation.instance.tracer end - def trace_response(span, response) - span.set_attribute('http.status_code', response.status) - span.status = OpenTelemetry::Trace::Status.error unless (100..399).cover?(response.status.to_i) + def trace_response(span, status) + span.set_attribute('http.status_code', status) + span.status = OpenTelemetry::Trace::Status.error unless (100..399).cover?(status.to_i) end end end diff --git a/instrumentation/faraday/test/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware_test.rb b/instrumentation/faraday/test/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware_test.rb index ffed5628f..acedc19d2 100644 --- a/instrumentation/faraday/test/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware_test.rb +++ b/instrumentation/faraday/test/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware_test.rb @@ -178,5 +178,25 @@ ) end end + + describe 'when faraday raises an error' do + let(:client) do + Faraday.new do |builder| + builder.response :raise_error + builder.adapter(:test) do |stub| + stub.get('/not_found') { |_| [404, {}, 'NOT FOUND'] } + end + end + end + + it 'adds response attributes' do + assert_raises Faraday::Error do + client.get('/not_found') + end + + _(span.attributes['http.status_code']).must_equal 404 + _(span.status.code).must_equal OpenTelemetry::Trace::Status::ERROR + end + end end end