传播

通过上下文传播,信号可以相互关联,无论它们在何处生成。虽然不仅限于追踪,但上下文传播允许追踪在跨越任意分布式进程和网络边界的服务中构建系统的因果信息。

对于绝大多数用例,原生支持 OpenTelemetry 的库或仪器库会为您自动跨服务传播追踪上下文。只有在极少数情况下,您才需要手动传播上下文。

要了解更多信息,请参阅上下文传播

自动上下文传播

分布式追踪超出了单个服务的范围,这意味着必须将某些上下文传播到远程服务以创建 Span 之间的父子关系。这需要跨服务上下文传播,这是一种将追踪标识符发送到远程进程的机制。

HTTP 框架和服务器的仪器库,如 PhoenixCowboyElli,以及客户端如 Tesla,会使用全局注册的传播器自动注入或提取上下文。默认情况下,使用的全局传播器是 W3C Trace ContextBaggage 格式。

您可以使用 OTP 应用程序环境变量 text_map_propagators 配置全局传播器

%% sys.config
...
{text_map_propagators, [baggage,
                        trace_context]},
...
## runtime.exs
...
text_map_propagators: [:baggage, :trace_context],
...

您还可以使用环境变量 OTEL_PROPAGATORS 传递逗号分隔的列表。这两种配置形式都接受 trace_contextbaggageb3b3multi 的值。

手动上下文传播

要手动注入或提取上下文,您可以使用 otel_propagator_text_map 模块

%% uses the context from the process dictionary to add to an empty list of headers
Headers = otel_propagator_text_map:inject([]),

%% creates a context in the process dictionary from Headers
otel_propagator_text_map:extract(Headers),
# uses the context from the process dictionary to add to an empty list of headers
headers = :otel_propagator_text_map.inject([])

# creates a context in the process dictionary from headers
:otel_propagator_text_map.extract(headers)

otel_propagator_text_map:inject/1otel_propagator_text_map:extract/1 使用全局注册的传播器。要使用特定的传播器,可以使用 otel_propagator_text_map:inject/2otel_propagator_text_map:extract/2,其中第一个参数是要调用的传播器模块的名称。

下一步

有关传播的更多信息,请阅读 传播器 API 规范