Skip to content

Correlate an operation context with the active OpenTelemetry span

Source: R/opentelemetry.R ยท Help: ?operation_context_from_otel

operation_context_from_otel() fills the trace_id and span_id of an operation context from the active span of the r-lib otel package, so that failure events written to logs with condition_to_event() carry the same identifiers as the trace.

Usage

operation_context_from_otel(context = NULL, span_context = NULL)

Arguments

context
An operation context to extend, or NULL for a new one.
span_context
The span context to read. NULL means otel's active span context.

Value

An operation context.

Details

Nothing is invented. When otel is not installed, tracing is off, or there is no valid active span, the context is returned unchanged. An identifier the context already has must agree with the span's: a conflicting trace_id or span_id is an error, because silently replacing provenance would make the correlation less trustworthy than omitting it.

Examples

context <- operation_context(system = "batch", operation = "settle_invoices")

# With tracing off there is no active span, so nothing is added.
operation_context_from_otel(context)

# Inside a traced operation, the trace and span identifiers are filled in.
# otelsdk records the trace in memory here, so no collector is needed.
if (requireNamespace("otelsdk", quietly = TRUE)) {
  settle_invoices <- function() {
    otel::start_local_active_span("settle_invoices")
    operation_context_from_otel(context)
  }
  traced <- otelsdk::with_otel_record(settle_invoices(), what = "traces")
  print(traced$value)

  # The identifiers are the recorded span's.
  identical(traced$value$trace_id, traced$traces[[1]]$trace_id)
}