Module: LlmLogs::Tracer

Defined in:
lib/llm_logs/tracer.rb

Class Method Summary collapse

Class Method Details

.auto_create_trace(span_name) ⇒ Object



66
67
68
69
70
71
72
73
74
# File 'lib/llm_logs/tracer.rb', line 66

def self.auto_create_trace(span_name)
  trace = LlmLogs::Trace.create!(
    name: "auto:#{span_name}",
    status: "running",
    started_at: Time.current
  )
  Fiber[:llm_logs_trace] = trace
  trace
end

.current_spanObject



12
13
14
# File 'lib/llm_logs/tracer.rb', line 12

def self.current_span
  Fiber[:llm_logs_span]
end

.current_span=(span) ⇒ Object



16
17
18
# File 'lib/llm_logs/tracer.rb', line 16

def self.current_span=(span)
  Fiber[:llm_logs_span] = span
end

.current_traceObject

Trace/span context is kept in Fiber-local storage (Fiber[]), which child fibers inherit on creation. This matters for fiber-based schedulers such as socketry/async: work driven inside a child fiber still sees the active trace. The legacy Thread.current store is not inherited by child fibers, which caused spans to auto-create orphan traces instead of nesting.



8
9
10
# File 'lib/llm_logs/tracer.rb', line 8

def self.current_trace
  Fiber[:llm_logs_trace]
end

.start_span(name:, span_type:, model: nil, provider: nil, input: nil, metadata: {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/llm_logs/tracer.rb', line 45

def self.start_span(name:, span_type:, model: nil, provider: nil, input: nil, metadata: {})
  trace = current_trace || auto_create_trace(name)
  parent = current_span

  span = LlmLogs::Span.create!(
    trace: trace,
    parent_span: parent,
    name: name,
    span_type: span_type,
    model: model,
    provider: provider,
    input: input,
    metadata: ,
    status: "ok",
    started_at: Time.current
  )

  Fiber[:llm_logs_span] = span
  span
end

.start_trace(name, metadata: {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/llm_logs/tracer.rb', line 20

def self.start_trace(name, metadata: {})
  trace = LlmLogs::Trace.create!(
    name: name,
    status: "running",
    metadata: ,
    started_at: Time.current
  )

  previous_trace = Fiber[:llm_logs_trace]
  previous_span = Fiber[:llm_logs_span]
  Fiber[:llm_logs_trace] = trace
  Fiber[:llm_logs_span] = nil

  begin
    yield trace
  rescue => e
    trace.fail!
    raise
  ensure
    trace.complete! if trace.status == "running"
    Fiber[:llm_logs_trace] = previous_trace
    Fiber[:llm_logs_span] = previous_span
  end
end