主要用于测试,例如

class MyClassTest
  def setup
    @tracer_provider = TracerProvider.new
    # The default is `recording: true`, which is appropriate in non-test environments.
    @exporter = InMemorySpanExporter.new(recording: false)
    @tracer_provider.add_span_processor(SimpleSampledSpansProcessor.new(@exporter))
  end

  def test_finished_spans
    @exporter.recording = true
    @tracer_provider.tracer.in_span("span") {}

    spans = @exporter.finished_spans
    spans.wont_be_nil
    spans.size.must_equal(1)
    spans[0].name.must_equal("span")

    @exporter.recording = false
  end
end

源码如下。export收集到span后,暂存在@finished_spans中。之后可使用finished_spans方法获取,使用reset方法清空

module OpenTelemetry
  module SDK
    module Trace
      module Export
        class InMemorySpanExporter
          def initialize(recording: true)
            @finished_spans = []
            @stopped = false
            @recording = recording
            @mutex = Mutex.new
          end

          def finished_spans
            @mutex.synchronize do
              @finished_spans.clone.freeze
            end
          end

          def reset
            @mutex.synchronize do
              @finished_spans.clear
            end
          end

          def export(span_datas, timeout: nil)
            @mutex.synchronize do
              return FAILURE if @stopped

              @finished_spans.concat(span_datas.to_a) if @recording
            end
            SUCCESS
          end
        end
      end
    end
  end
end