Module: OpenTrace

Defined in:
lib/opentrace.rb,
lib/opentrace/ulid.rb,
lib/opentrace/rails.rb,
lib/opentrace/stats.rb,
lib/opentrace/client.rb,
lib/opentrace/config.rb,
lib/opentrace/logger.rb,
lib/opentrace/sampler.rb,
lib/opentrace/version.rb,
lib/opentrace/pipeline.rb,
lib/opentrace/local_vars.rb,
lib/opentrace/middleware.rb,
lib/opentrace/serializer.rb,
lib/opentrace/breadcrumbs.rb,
lib/opentrace/buffer_pool.rb,
lib/opentrace/ring_buffer.rb,
lib/opentrace/http_tracker.rb,
lib/opentrace/memory_guard.rb,
lib/opentrace/pii_scrubber.rb,
lib/opentrace/pool_monitor.rb,
lib/opentrace/audit_tracker.rb,
lib/opentrace/capture_rules.rb,
lib/opentrace/log_forwarder.rb,
lib/opentrace/queue_monitor.rb,
lib/opentrace/trace_context.rb,
lib/opentrace/request_buffer.rb,
lib/opentrace/source_context.rb,
lib/opentrace/sql_normalizer.rb,
lib/opentrace/circuit_breaker.rb,
lib/opentrace/payload_builder.rb,
lib/opentrace/runtime_monitor.rb,
lib/opentrace/trace_formatter.rb,
lib/opentrace/error_subscriber.rb,
lib/opentrace/request_collector.rb,
lib/opentrace/instrumentation_context.rb

Defined Under Namespace

Modules: AuditTracker, HttpTracker, LocalVars, PayloadBuilder, PiiScrubber, Serializer, SourceContext, SqlNormalizer, TraceContext, ULID Classes: Breadcrumb, BreadcrumbBuffer, BufferPool, CaptureRules, CircuitBreaker, Client, Config, ErrorSubscriber, InstrumentationContext, LogForwarder, Logger, MemoryGuard, Middleware, NilClient, NilSpan, NilStats, Pipeline, PipelineStats, PoolMonitor, QueueMonitor, Railtie, RequestBuffer, RequestCollector, RingBuffer, RuntimeMonitor, Sampler, Span, Stats, TraceFormatter

Constant Summary collapse

LEVEL_VALUES =
{ "DEBUG" => 0, "INFO" => 1, "WARN" => 2, "ERROR" => 3, "FATAL" => 4 }.freeze
NULL_CLIENT =
NilClient.new.freeze
VERSION =
"0.17.0"

Class Method Summary collapse

Class Method Details

.add_breadcrumb(category, message, data = nil, level: "info") ⇒ Object

Add a breadcrumb to the current request’s trail.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/opentrace.rb', line 242

def add_breadcrumb(category, message, data = nil, level: "info")
  return unless enabled?
  buffer = Fiber[:opentrace_breadcrumbs] ||= BreadcrumbBuffer.new

  crumb = Breadcrumb.new(category: category, message: message, data: data, level: level)
  if config.before_breadcrumb
    crumb = config.before_breadcrumb.call(crumb) rescue crumb
    return unless crumb
  end

  buffer.add(crumb)
rescue StandardError
  # Never raise
end

.capture_binding(exception, binding_obj) ⇒ Object



261
262
263
264
265
266
267
268
269
270
# File 'lib/opentrace.rb', line 261

def capture_binding(exception, binding_obj)
  return unless enabled? && config.local_vars_capture

  vars = LocalVars.capture(binding_obj)
  if vars && !vars.empty?
    exception.instance_variable_set(:@__opentrace_local_vars__, vars)
  end
rescue StandardError
  # Never raise
end

.client_enqueue_raw(doc) ⇒ Object

Enqueue a raw request buffer document (from InstrumentationContext). Converts the nested buffer doc to flat format before enqueueing.



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/opentrace.rb', line 293

def client_enqueue_raw(doc)
  return unless enabled?

  req = doc[:request] || {}
  resp = doc[:response] || {}
  duration_ms = if doc[:started_at]
                  ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - doc[:started_at]) * 1000).round(0)
                end

  status = resp[:status] || resp[:response_status]
  level = if status.to_i >= 500 then "error"
         elsif status.to_i >= 400 then "warn"
         else "info"
         end

  message = "#{req[:method]} #{req[:path]} #{status} #{duration_ms}ms"

  payload = {
    ts: Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%6NZ"),
    level: level,
    service: config.service,
    env: config.environment,
    message: message,
    event_type: "http.request",
    method: req[:method],
    path: req[:path],
    status: status.to_i,
    duration_ms: duration_ms.to_i,
    controller: doc[:controller],
  }

  payload[:trace_id] = doc[:trace_id] if doc[:trace_id]
  payload[:span_id] = doc[:span_id] if doc[:span_id]
  payload[:parent_span_id] = doc[:parent_span_id] if doc[:parent_span_id]
  payload[:request_id] = doc[:request_id] if doc[:request_id]

  # Pack everything else into body
  body = {}
  body[:request_headers] = req[:headers] if req[:headers]
  body[:request_params] = req[:params] if req[:params]
  body[:request_body] = req[:body] if req[:body]
  body[:response_headers] = resp[:headers] if resp[:headers]
  body[:response_body] = resp[:body] if resp[:body]
  body[:sql] = doc[:sql] if doc[:sql] && !doc[:sql].empty?
  body[:http] = doc[:http] if doc[:http] && !doc[:http].empty?
  body[:email] = doc[:email] if doc[:email] && !doc[:email].empty?
  body[:audit] = doc[:audit] if doc[:audit] && !doc[:audit].empty?
  body[:logs] = doc[:logs] if doc[:logs] && !doc[:logs].empty?
  body[:timeline] = doc[:timeline] if doc[:timeline] && !doc[:timeline].empty?
  body[:performance] = doc[:performance] if doc[:performance]
  body[:context] = doc[:context] if doc[:context]

  payload[:body] = body unless body.empty?
  client.enqueue(payload)
rescue StandardError
  # Never raise to the host app
end

.configObject



67
68
69
# File 'lib/opentrace.rb', line 67

def config
  @config ||= Config.new
end

.configure {|config| ... } ⇒ Object

Yields:



61
62
63
64
65
# File 'lib/opentrace.rb', line 61

def configure
  yield config
  config.finalize!
  reset_client!
end

.current_breadcrumbsObject



257
258
259
# File 'lib/opentrace.rb', line 257

def current_breadcrumbs
  Fiber[:opentrace_breadcrumbs]&.to_a || []
end

.current_request_idObject



193
194
195
# File 'lib/opentrace.rb', line 193

def current_request_id
  Fiber[:opentrace_request_id]
end

.current_request_id=(id) ⇒ Object



197
198
199
# File 'lib/opentrace.rb', line 197

def current_request_id=(id)
  Fiber[:opentrace_request_id] = id
end

.current_transaction_nameObject



208
209
210
# File 'lib/opentrace.rb', line 208

def current_transaction_name
  Fiber[:opentrace_transaction_name]
end

.disable!Object



185
186
187
# File 'lib/opentrace.rb', line 185

def disable!
  config.enabled = false
end

.enable!Object



189
190
191
# File 'lib/opentrace.rb', line 189

def enable!
  config.enabled = true
end

.enabled?Boolean

Returns:

  • (Boolean)


181
182
183
# File 'lib/opentrace.rb', line 181

def enabled?
  config.enabled?
end

.error(exception, metadata = {}) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/opentrace.rb', line 99

def error(exception,  = {})
  return unless enabled?
  return if Fiber[:opentrace_logging]
  Fiber[:opentrace_logging] = true

  begin
    meta = .is_a?(Hash) ? .dup : {}
    meta[:exception_class]   = exception.class.name
    meta[:exception_message] = exception.message&.slice(0, 500)

    if exception.backtrace
      cleaned = clean_backtrace_for(exception)
      meta[:backtrace] = cleaned.first(15)
    end

    # Capture exception cause chain (max 5 deep)
    if exception.cause
      meta[:exception_causes] = build_cause_chain(exception.cause, depth: 0)
    end

    # Capture source code context for the error origin
    if exception.backtrace && config.source_context
      cleaned = meta[:backtrace] || clean_backtrace_for(exception)
      app_frame = cleaned&.first
      if app_frame
        source = SourceContext.extract(app_frame)
        meta[:source_context] = source if source
      end
    end

    # Attach current breadcrumbs to error
    crumbs = Fiber[:opentrace_breadcrumbs]
    if crumbs && !crumbs.empty?
      meta[:breadcrumbs] = crumbs.to_a
    end

    # Attach captured local variables (if capture_binding was called)
    if config.local_vars_capture && exception.instance_variable_defined?(:@__opentrace_local_vars__)
      meta[:local_variables] = exception.instance_variable_get(:@__opentrace_local_vars__)
    end

    # Fire on_error callback
    config.on_error&.call(exception, meta) rescue nil

    buffer = Fiber[:opentrace_buffer]
    if buffer
      # Inside a request -- record to buffer
      buffer.record_log(level: "ERROR", message: exception.message.to_s, metadata: meta)
      buffer.record_timeline(type: :error, name: "#{exception.class.name}: #{exception.message.to_s[0, 60]}")
    else
      doc = build_standalone_doc("ERROR", exception.message.to_s, meta, event_type: "error")
      client.enqueue(doc)
    end
  ensure
    Fiber[:opentrace_logging] = nil
  end
rescue StandardError
  # Never raise to the host app
end

.event(event_type, message, metadata = {}) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/opentrace.rb', line 159

def event(event_type, message,  = {})
  return unless enabled?
  return if Fiber[:opentrace_logging]
  Fiber[:opentrace_logging] = true

  begin
    buffer = Fiber[:opentrace_buffer]
    if buffer
      # Inside a request -- record to buffer
      buffer.record_log(level: "INFO", message: message.to_s, metadata: .merge(_event_type: event_type))
      buffer.record_timeline(type: :event, name: "#{event_type}: #{message.to_s[0, 60]}")
    else
      doc = build_standalone_doc("INFO", message.to_s, , event_type: event_type.to_s)
      client.enqueue(doc)
    end
  ensure
    Fiber[:opentrace_logging] = nil
  end
rescue StandardError
  # Never raise to the host app
end

.healthy?Boolean

Returns:

  • (Boolean)


281
282
283
284
285
# File 'lib/opentrace.rb', line 281

def healthy?
  return false unless @client
  snapshot = @client.stats_snapshot
  snapshot[:circuit_state] == :closed && !snapshot[:auth_suspended]
end

.log(level, message, metadata = {}) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/opentrace.rb', line 75

def log(level, message,  = {})
  return unless enabled?
  return unless config.level_allowed?(level)
  return if Fiber[:opentrace_logging]
  Fiber[:opentrace_logging] = true

  begin
    buffer = Fiber[:opentrace_buffer]
    if buffer
      # Inside a request -- append to buffer
      buffer.record_log(level: level.to_s.upcase, message: message.to_s, metadata: )
      buffer.record_timeline(type: :log, name: message.to_s[0, 80])
    else
      # Standalone log -- build lightweight document and enqueue
      doc = build_standalone_doc(level, message.to_s, )
      client.enqueue(doc)
    end
  ensure
    Fiber[:opentrace_logging] = nil
  end
rescue StandardError
  # Never raise to the host app
end

.reset!Object



351
352
353
354
355
356
357
358
359
# File 'lib/opentrace.rb', line 351

def reset!
  shutdown(timeout: 1)
  @config = nil
  @client = nil
  @static_context = nil
  @sampler = nil
  @at_exit_registered = nil
  InstrumentationContext.reset!
end

.reset_stats!Object



277
278
279
# File 'lib/opentrace.rb', line 277

def reset_stats!
  @client&.stats&.reset!
end

.samplerObject



71
72
73
# File 'lib/opentrace.rb', line 71

def sampler
  @sampler ||= Sampler.new(config)
end

.set_transaction_name(name) ⇒ Object

Override the auto-detected transaction name for the current request.



202
203
204
205
206
# File 'lib/opentrace.rb', line 202

def set_transaction_name(name)
  Fiber[:opentrace_transaction_name] = name.to_s
rescue StandardError
  # Never raise
end

.shutdown(timeout: 5) ⇒ Object



287
288
289
# File 'lib/opentrace.rb', line 287

def shutdown(timeout: 5)
  @client&.shutdown(timeout: timeout)
end

.statsObject



272
273
274
275
# File 'lib/opentrace.rb', line 272

def stats
  return {} unless @client
  @client.stats_snapshot
end

.trace(operation_name, resource: nil, tags: {}) ⇒ Object

Trace a block of code, recording its duration as a span.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/opentrace.rb', line 213

def trace(operation_name, resource: nil, tags: {})
  return yield(NilSpan::INSTANCE) unless enabled?

  begin
    span = Span.new(
      operation: operation_name,
      resource: resource,
      parent_span_id: Fiber[:opentrace_span_id],
      trace_id: Fiber[:opentrace_trace_id]
    )
    previous_span_id = Fiber[:opentrace_span_id]
    Fiber[:opentrace_span_id] = span.span_id
  rescue StandardError
    return yield(NilSpan::INSTANCE)
  end

  begin
    result = yield(span)
    span.finish(tags: tags)
    result
  rescue => e
    span.finish(error: e, tags: tags)
    raise
  ensure
    Fiber[:opentrace_span_id] = previous_span_id
  end
end