Class: OpenTrace::Span

Inherits:
Object
  • Object
show all
Defined in:
lib/opentrace.rb

Overview

A timed span for custom instrumentation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(operation:, resource:, parent_span_id:, trace_id:) ⇒ Span

Returns a new instance of Span.



460
461
462
463
464
465
466
467
468
469
# File 'lib/opentrace.rb', line 460

def initialize(operation:, resource:, parent_span_id:, trace_id:)
  @operation = operation
  @resource = resource
  @span_id = TraceContext.generate_span_id
  @parent_span_id = parent_span_id
  @trace_id = trace_id
  @start = Process.clock_gettime(Process::CLOCK_REALTIME)
  @tags = {}
  @finished = false
end

Instance Attribute Details

#operationObject (readonly)

Returns the value of attribute operation.



458
459
460
# File 'lib/opentrace.rb', line 458

def operation
  @operation
end

#resourceObject (readonly)

Returns the value of attribute resource.



458
459
460
# File 'lib/opentrace.rb', line 458

def resource
  @resource
end

#span_idObject (readonly)

Returns the value of attribute span_id.



458
459
460
# File 'lib/opentrace.rb', line 458

def span_id
  @span_id
end

Instance Method Details

#finish(error: nil, tags: {}) ⇒ Object



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/opentrace.rb', line 475

def finish(error: nil, tags: {})
  return if @finished
  @finished = true
  duration = Process.clock_gettime(Process::CLOCK_REALTIME) - @start

  meta = @tags.merge(tags)
  meta[:span_operation] = @operation
  meta[:span_resource] = @resource if @resource
  meta[:span_duration_ms] = (duration * 1000).round(2)

  if error
    meta[:exception_class] = error.class.name
    meta[:exception_message] = error.message&.slice(0, 500)
  end

  level = error ? "ERROR" : "INFO"
  OpenTrace.log(level, "span:#{@operation}", meta)

  # Record in RequestCollector timeline if present
  collector = Fiber[:opentrace_collector]
  collector&.record_span(operation: @operation, duration_ms: meta[:span_duration_ms])
rescue StandardError
  # Never raise
end

#set_tag(key, value) ⇒ Object



471
472
473
# File 'lib/opentrace.rb', line 471

def set_tag(key, value)
  @tags[key] = value
end