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.



433
434
435
436
437
438
439
440
441
442
# File 'lib/opentrace.rb', line 433

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.



431
432
433
# File 'lib/opentrace.rb', line 431

def operation
  @operation
end

#resourceObject (readonly)

Returns the value of attribute resource.



431
432
433
# File 'lib/opentrace.rb', line 431

def resource
  @resource
end

#span_idObject (readonly)

Returns the value of attribute span_id.



431
432
433
# File 'lib/opentrace.rb', line 431

def span_id
  @span_id
end

Instance Method Details

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



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/opentrace.rb', line 448

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



444
445
446
# File 'lib/opentrace.rb', line 444

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