Sha256: 943a8aa12066151a93aa47163050df937bacdbfa2b781c2fe0464d147510e436

Contents?: true

Size: 1.69 KB

Versions: 2

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

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

module OpenTelemetry
  module Adapters
    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: {
                'component' => 'http',
                'http.method' => http_method,
                'http.url' => env.url.to_s
              },
              kind: :client
            ) do |span|
              OpenTelemetry.propagation.http.inject(env.request_headers)

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

          private

          attr_reader :app

          def tracer
            Faraday::Adapter.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

2 entries across 2 versions & 1 rubygems

Version Path
opentelemetry-adapters-faraday-0.4.0 lib/opentelemetry/adapters/faraday/middlewares/tracer_middleware.rb
opentelemetry-adapters-faraday-0.3.0 lib/opentelemetry/adapters/faraday/middlewares/tracer_middleware.rb