Sha256: 2c7a8725c30dd1be89b9bcd2d666d1724e5f9c564429fdde74b43028c81977f2

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

# Copyright The OpenTelemetry Authors
#
# SPDX-License-Identifier: Apache-2.0

module OpenTelemetry
  module Instrumentation
    module Faraday
      module Middlewares
        # TracerMiddleware propagates context and instruments Faraday requests
        # by way of its middlware system
        class TracerMiddleware < ::Faraday::Middleware
          HTTP_METHODS_SYMBOL_TO_STRING = {
            connect: 'CONNECT',
            delete: 'DELETE',
            get: 'GET',
            head: 'HEAD',
            options: 'OPTIONS',
            patch: 'PATCH',
            post: 'POST',
            put: 'PUT',
            trace: 'TRACE'
          }.freeze

          def call(env)
            http_method = HTTP_METHODS_SYMBOL_TO_STRING[env.method]

            tracer.in_span(
              "HTTP #{http_method}",
              attributes: {
                'http.method' => http_method,
                'http.url' => env.url.to_s
              },
              kind: :client
            ) do |span|
              OpenTelemetry.propagation.inject(env.request_headers)

              app.call(env).on_complete { |resp| trace_response(span, resp) }
            end
          end

          private

          attr_reader :app

          def tracer
            Faraday::Instrumentation.instance.tracer
          end

          def trace_response(span, response)
            span.set_attribute('http.status_code', response.status)
            span.set_attribute('http.status_text', response.reason_phrase)
            span.status = OpenTelemetry::Trace::Status.http_to_status(
              response.status
            )
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
opentelemetry-instrumentation-faraday-0.14.0 lib/opentelemetry/instrumentation/faraday/middlewares/tracer_middleware.rb