lib/rspec/trace/consumer.rb in rspec-trace-formatter-0.1.0 vs lib/rspec/trace/consumer.rb in rspec-trace-formatter-0.2.0
- old
+ new
@@ -5,22 +5,17 @@
require "opentelemetry/exporter/otlp"
module RSpec
module Trace
class Consumer
- def initialize(input)
+ def initialize(input, traceparent_string = nil)
@input = input
- OpenTelemetry::SDK.configure do |c|
- c.service_name = ENV.fetch("OTEL_SERVICE_NAME", "rspec")
- end
@tracer_provider = OpenTelemetry.tracer_provider
@tracer_provider.sampler = OpenTelemetry::SDK::Trace::Samplers::ALWAYS_ON
@tracer = @tracer_provider.tracer("rspec-trace-formatter", RSpec::Trace::VERSION)
@spans = []
- # TODO: Not this
- @current_span_key = OpenTelemetry::Trace.const_get(:CURRENT_SPAN_KEY)
- @contexts = [OpenTelemetry::Context.empty]
+ @contexts = [load_context_from_traceparent(traceparent_string)]
@tokens = []
end
def run
@input.each_line do |line|
@@ -108,21 +103,30 @@
end
end
private
+ def load_context_from_traceparent(traceparent_string)
+ return OpenTelemetry::Context.current unless traceparent_string
+
+ OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator.extract(
+ {"traceparent" => traceparent_string}
+ )
+ end
+
def parse_event(line)
event = JSON.parse(line, symbolize_names: true)
event[:timestamp] = Time.parse(event[:timestamp])
event
end
def create_span(name:, timestamp:)
@tracer.start_span(name, start_timestamp: timestamp, with_parent: @contexts.last).tap do |span|
yield span if block_given?
@spans.push(span)
- @contexts.push(@contexts.last.set_value(@current_span_key, span))
- @tokens.push(OpenTelemetry::Context.attach(@contexts.last))
+ new_context = OpenTelemetry::Trace.context_with_span(span, parent_context: @contexts.last)
+ @contexts.push(new_context)
+ @tokens.push(OpenTelemetry::Context.attach(new_context))
end
end
def complete_span(timestamp:)
@spans.pop.tap do |span|