Module: NetHttpPatch::Instrumentation

Defined in:
lib/helios/opentelemetry/sdk/patches/net_http_patch.rb

Overview

Module to prepend to Net::HTTP for instrumentation

Instance Method Summary collapse

Instance Method Details

#collect_headers(obj) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/helios/opentelemetry/sdk/patches/net_http_patch.rb', line 17

def collect_headers(obj)
  headers = {}
  obj.each_header do |k, v|
    headers[k] = v
  end

  headers.to_json
end

#extract_request_attributes(span, req, body) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/helios/opentelemetry/sdk/patches/net_http_patch.rb', line 26

def extract_request_attributes(span, req, body)
  span.set_attribute(Helios::OpenTelemetry::SemanticAttributes::HTTP_REQUEST_HEADERS, collect_headers(req))
  unless body.nil?
    span.set_attribute(Helios::OpenTelemetry::SemanticAttributes::HTTP_REQUEST_BODY,
                       body.is_a?(String) ? body : body.to_s)
  end

  url = req.uri&.to_s
  sem_conv = OpenTelemetry::SemanticConventions::Trace
  if url.nil?
    scheme = span.attributes[sem_conv::HTTP_SCHEME]
    hostname = span.attributes[sem_conv::HTTP_HOST] || span.attributes[sem_conv::NET_PEER_NAME]
    target = span.attributes[sem_conv::HTTP_TARGET]
    url = "#{scheme}://#{hostname}#{target}" if scheme && hostname && target
  end

  span.set_attribute(sem_conv::HTTP_URL, url) unless url.nil?
rescue StandardError => e
  ::OpenTelemetry.logger.debug("Error extracting net http request attributes: #{e}")
end

#extract_response_attributes(span, response) ⇒ Object



47
48
49
50
51
52
# File 'lib/helios/opentelemetry/sdk/patches/net_http_patch.rb', line 47

def extract_response_attributes(span, response)
  span.set_attribute(Helios::OpenTelemetry::SemanticAttributes::HTTP_RESPONSE_HEADERS, collect_headers(response))
  span.set_attribute(Helios::OpenTelemetry::SemanticAttributes::HTTP_RESPONSE_BODY, response.body)
rescue StandardError => e
  ::OpenTelemetry.logger.debug("Error extracting net http response attributes: #{e}")
end

#request(req, body = nil, &block) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/helios/opentelemetry/sdk/patches/net_http_patch.rb', line 8

def request(req, body = nil, &block)
  current_span = OpenTelemetry::Trace.current_span
  extract_request_attributes(current_span, req, body)

  super(req, body, &block).tap do |response|
    extract_response_attributes(current_span, response)
  end
end