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.



481
482
483
484
485
486
487
488
489
490
# File 'lib/opentrace.rb', line 481

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.



479
480
481
# File 'lib/opentrace.rb', line 479

def operation
  @operation
end

#resourceObject (readonly)

Returns the value of attribute resource.



479
480
481
# File 'lib/opentrace.rb', line 479

def resource
  @resource
end

#span_idObject (readonly)

Returns the value of attribute span_id.



479
480
481
# File 'lib/opentrace.rb', line 479

def span_id
  @span_id
end

Instance Method Details

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



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/opentrace.rb', line 496

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 RequestBuffer timeline if present
  buffer = Fiber[:opentrace_buffer]
  buffer&.record_timeline(type: :span, name: @operation, duration_ms: meta[:span_duration_ms])
rescue StandardError
  # Never raise
end

#set_tag(key, value) ⇒ Object



492
493
494
# File 'lib/opentrace.rb', line 492

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