Language APIs & SDKs-C++-Instrumentation

2024-05-24 19:22:22 浏览数 (2)

装置

  • *Instrumentation*
    • *Setup*
    • *Traces*
      • *Initializing tracing*
      • *Start a span*
      • *Mark a span as active*
      • *Create nested Spans*
      • *Context Propagation*
      • *Further Reading*
    • *Metrics*
      • *Initialize Exporter and Reader*
      • *Initialize Meter Provider*
      • *Create a Counter*
      • *Create a Histogram*
      • *Create Observable Counter*
      • *Create Views*
        • *Map the Counter Instrument to Sum Aggregation*
        • *Map the Histogram Instrument to Histogram Aggregation*
        • *Map the Observable Counter Instrument to Sum Aggregation*
      • *Further Reading*
    • *Logs*
  • *Next Steps*

Instrumentation

测量装置

Instrumentation for OpenTelemetry C OpenTelemetry C 测量装置

Instrumentation is the act of adding observability code to an app yourself. 测量是您自己向应用程序添加可观测性代码的行为。

If you’re instrumenting an app, you need to use the OpenTelemetry SDK for your language. You’ll then use the SDK to initialize OpenTelemetry and the API to instrument your code. This will emit telemetry from your app, and any library you installed that also comes with instrumentation. 如果您要测量一款应用程序,则需要使用适合您语言的 OpenTelemetry SDK。然后,您将使用SDK初始化 OpenTelemetry并使用API来测量您的代码。这将从您的应用程序以及您安装的任何也附带测量装置的库发出遥测数据。

If you’re instrumenting a library, only install the OpenTelemetry API package for your language. Your library will not emit telemetry on its own. It will only emit telemetry when it is part of an app that uses the OpenTelemetry SDK. For more on instrumenting libraries, see Libraries. 如果您要测量库,请仅安装适合您的语言的OpenTelemetry API包。您的库不会自行发出遥测数据。仅当它是使用 OpenTelemetry SDK的应用程序的一部分时,它才会发出遥测数据。有关检测库的更多信息,请参阅库。

For more information about the OpenTelemetry API and SDK, see the specification. 有关OpenTelemetry API和SDK的更多信息,请参阅规范。

Setup

设置

Follow the instructions in the Getting Started Guide to build OpenTelemetry C . 按照入门指南中的说明 构建OpenTelemetry C 。

Traces

Initializing tracing

初始化跟踪

代码语言:javascript复制
auto provider = opentelemetry::trace::Provider::GetTracerProvider();
auto tracer = provider->GetTracer("foo_library", "1.0.0");

The TracerProvider acquired in the first step is a singleton object that is usually provided by the OpenTelemetry C SDK. It is used to provide specific implementations for API interfaces. In case no SDK is used, the API provides a default no-op implementation of a TracerProvider. TracerProvider第一步获取的是一个单例对象,通常由OpenTelemetry C SDK提供。它用于提供API接口的具体实现。如果未使用 SDK,API 会提供TracerProvider.

The Tracer acquired in the second step is needed to create and start Spans. Tracer会在第二部创建和启动Spans中被使用。

Start a span
代码语言:javascript复制
auto span = tracer->StartSpan("HandleRequest");

This creates a span, sets its name to “HandleRequest”, and sets its start time to the current time. Refer to the API documentation for other operations that are available to enrich spans with additional data. 这将创建一个Span,将其名称设置为"HandleRequest",并将其开始时间设置为当前时间。请参阅API文档,了解可用于通过附加数据丰富Span的其他操作。

Mark a span as active

将Span标记为活动

代码语言:javascript复制
auto scope = tracer->WithActiveSpan(span);

This marks a span as active and returns a Scope object. The scope object controls how long a span is active. The span remains active for the lifetime of the scope object. 这将 Span 标记为活动状态并返回一个Scope对象。范围对象控制Span的活动时间。Span在范围对象的生命周期内保持活动状态。

The concept of an active span is important, as any span that is created without explicitly specifying a parent is parented to the currently active span. A span without a parent is called root span. 活动Span的概念很重要,因为在没有显式指定父级的情况下创建的任何Span都是当前活动Span的父级。没有父级的Span称为Root Span。

Create nested Spans

创建嵌套 Span

代码语言:javascript复制
auto outer_span = tracer->StartSpan("Outer operation");
auto outer_scope = tracer->WithActiveSpan(outer_span);
{
    auto inner_span = tracer->StartSpan("Inner operation");
    auto inner_scope = tracer->WithActiveSpan(inner_span);
    // ... perform inner operation
    inner_span->End();
}
// ... perform outer operation
outer_span->End();

Spans can be nested, and have a parent-child relationship with other spans. When a given span is active, the newly created span inherits the active span’s trace ID, and other context attributes. Span可以嵌套,并且与其他Span具有父子关系。当给定Span处于活动状态时,新创建的Span将继承活动Span的trace ID和其他上下文属性。

Context Propagation

上下文传播

代码语言:javascript复制
// set global propagator
opentelemetry::context::propagation::GlobalTextMapPropagator::SetGlobalPropagator(
    nostd::shared_ptr<opentelemetry::context::propagation::TextMapPropagator>(
        new opentelemetry::trace::propagation::HttpTraceContext()));

// get global propagator
HttpTextMapCarrier<opentelemetry::ext::http::client::Headers> carrier;
auto propagator =
    opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator();

//inject context to headers
auto current_ctx = opentelemetry::context::RuntimeContext::GetCurrent();
propagator->Inject(carrier, current_ctx);

//Extract headers to context
auto current_ctx = opentelemetry::context::RuntimeContext::GetCurrent();
auto new_context = propagator->Extract(carrier, current_ctx);
auto remote_span = opentelemetry::trace::propagation::GetSpan(new_context);

Context contains the metadata of the currently active Span including Span ID, Trace ID, and flags. Context Propagation is an important mechanism in distributed tracing to transfer this Context across service boundary often through HTTP headers. OpenTelemetry provides a text-based approach to propagate context to remote services using the W3C Trace Context HTTP headers. Context包含当前活动 Span 的元数据,包括 Span ID、Trace ID 和标志。上下文传播是分布式跟踪中的一种重要机制,通常通过 HTTP 标头跨服务边界传输此上下文。 OpenTelemetry 提供了一种基于文本的方法,使用 W3C 跟踪上下文 HTTP 标头将上下文传播到远程服务。

Further Reading

进一步阅读

  • *Traces API *
  • *Traces SDK *
  • Simple Metrics Example

Metrics

Initialize Exporter and Reader

初始化导出器和读取器

Initialize an exporter and a reader. In this case, we initialize an OStream Exporter which will print to stdout by default. The reader periodically collects metrics from the Aggregation Store and exports them. 初始化导出器和读取器。在本例中,我们初始化一个 OStream Exporter,默认情况下它将打印到 stdout。读取器定期从聚合存储收集指标并导出它们。

代码语言:javascript复制
std::unique_ptr<opentelemetry::sdk::metrics::MetricExporter> exporter{new opentelemetry::exporters::OStreamMetricExporter};
std::unique_ptr<opentelemetry::sdk::metrics::MetricReader> reader{
    new opentelemetry::sdk::metrics::PeriodicExportingMetricReader(std::move(exporter), options)};
Initialize Meter Provider

初始化Meter Provider

Initialize a MeterProvider and add the reader. We will use this to obtain Meter objects in the future. 初始化MeterProvider并添加读取器。以后我们将用它来获取Meter对象。

代码语言:javascript复制
auto provider = std::shared_ptr<opentelemetry::metrics::MeterProvider>(new opentelemetry::sdk::metrics::MeterProvider());
auto p = std::static_pointer_cast<opentelemetry::sdk::metrics::MeterProvider>(provider);
p->AddMetricReader(std::move(reader));
Create a Counter

创建一个计数器

Create a Counter instrument from the Meter, and record the measurement. Every Meter pointer returned by the MeterProvider points to the same Meter. This means that the Meter will be able to combine metrics captured from different functions without having to constantly pass the Meter around the library. 从Meter创建计数器装置,并记录测量结果。MeterProvider返回的每个Meter指针都指向同一个Meter。这意味着 Meter将能够组合从不同函数捕获的指标,而无需不断地在库中传递 Meter。

代码语言:javascript复制
auto meter = provider->GetMeter(name, "1.2.0");
auto double_counter = meter->CreateDoubleCounter(counter_name);
// Create a label set which annotates metric values
std::map<std::string, std::string> labels = {{"key", "value"}};
auto labelkv = common::KeyValueIterableView<decltype(labels)>{labels};
double_counter->Add(val, labelkv);
Create a Histogram

创建直方图

Create a Histogram instrument from the Meter, and record the measurement. 从Meter创建直方图装置,并记录测量结果。

代码语言:javascript复制
auto meter = provider->GetMeter(name, "1.2.0");
auto histogram_counter = meter->CreateDoubleHistogram("histogram_name");
histogram_counter->Record(val, labelkv);
Create Observable Counter

创建可观测计数器

Create a Observable Counter Instrument from the Meter, and add a callback. The callback would be used to record the measurement during metrics collection. Ensure to keep the Instrument object active for the lifetime of collection. 从仪表创建可观察的计数器工具,并添加回调。回调将用于记录指标收集期间的测量结果。确保 Instrument 对象在集合的生命周期内保持活动状态。

代码语言:javascript复制
auto meter = provider->GetMeter(name, "1.2.0");
auto counter = meter->CreateDoubleObservableCounter(counter_name);
counter->AddCallback(MeasurementFetcher::Fetcher, nullptr);
Create Views

创建视图

Map the Counter Instrument to Sum Aggregation

将计数器装置映射到求和聚合

Create a view to map the Counter Instrument to Sum Aggregation. Add this view to provider. View creation is optional unless we want to add custom aggregation config, and attribute processor. Metrics SDK will implicitly create a missing view with default mapping between Instrument and Aggregation. 创建一个视图以将计数器装置映射到求和聚合。将此视图添加到Provider。除非我们想添加自定义聚合配置和属性处理器,否则视图创建是可选的。 Metrics SDK 将隐式创建一个缺失的视图,其中包含装置和聚合之间的默认映射。

代码语言:javascript复制
std::unique_ptr<opentelemetry::sdk::metrics::InstrumentSelector> instrument_selector{
    new opentelemetry::sdk::metrics::InstrumentSelector(opentelemetry::sdk::metrics::InstrumentType::kCounter, "counter_name")};
std::unique_ptr<opentelemetry::sdk::metrics::MeterSelector> meter_selector{
    new opentelemetry::sdk::metrics::MeterSelector(name, version, schema)};
std::unique_ptr<opentelemetry::sdk::metrics::View> sum_view{
    new opentelemetry::sdk::metrics::View{name, "description", opentelemetry::sdk::metrics::AggregationType::kSum}};
p->AddView(std::move(instrument_selector), std::move(meter_selector), std::move(sum_view));
Map the Histogram Instrument to Histogram Aggregation

将直方图装置映射到直方图聚合

代码语言:javascript复制
std::unique_ptr<opentelemetry::sdk::metrics::InstrumentSelector> histogram_instrument_selector{
    new opentelemetry::sdk::metrics::InstrumentSelector(opentelemetry::sdk::metrics::InstrumentType::kHistogram, "histogram_name")};
std::unique_ptr<opentelemetry::sdk::metrics::MeterSelector> histogram_meter_selector{
    new opentelemetry::sdk::metrics::MeterSelector(name, version, schema)};
std::unique_ptr<opentelemetry::sdk::metrics::View> histogram_view{
    new opentelemetry::sdk::metrics::View{name, "description", opentelemetry::sdk::metrics::AggregationType::kHistogram}};
p->AddView(std::move(histogram_instrument_selector), std::move(histogram_meter_selector),
    std::move(histogram_view));
Map the Observable Counter Instrument to Sum Aggregation

将可观察计数器装置映射到求和聚合

代码语言:javascript复制
std::unique_ptr<opentelemetry::sdk::metrics::InstrumentSelector> observable_instrument_selector{
    new opentelemetry::sdk::metrics::InstrumentSelector(opentelemetry::sdk::metrics::InstrumentType::kObservableCounter,
                                     "observable_counter_name")};
std::unique_ptr<opentelemetry::sdk::metrics::MeterSelector> observable_meter_selector{
  new opentelemetry::sdk::metrics::MeterSelector(name, version, schema)};
std::unique_ptr<opentelemetry::sdk::metrics::View> observable_sum_view{
  new opentelemetry::sdk::metrics::View{name, "description", opentelemetry::sdk::metrics::AggregationType::kSum}};
p->AddView(std::move(observable_instrument_selector), std::move(observable_meter_selector),
         std::move(observable_sum_view));
Further Reading
  • Metrics API
  • Metrics SDK
  • Simple Metrics Example

Logs

The documentation for the logs API & SDK is missing, you can help make it available by editing this page .

Next Steps

You’ll also want to configure an appropriate exporter to export your telemetry data to one or more telemetry backends. 您还需要配置适当的导出器以将遥测数据导出到一个或多个遥测后端。

0 人点赞