全部产品
Search
文档中心

可观测链路 OpenTelemetry 版:通过OpenTelemetry上报C++应用数据

更新时间:Aug 07, 2024

通过OpenTelemetry为应用埋点并上报链路数据至可观测链路 OpenTelemetry 版后,可观测链路 OpenTelemetry 版即可开始监控应用,您可以查看应用拓扑、调用链路、异常事务、慢事务和SQL分析等一系列监控数据。本文介绍如何使用OpenTelemetry为C++应用埋点并上报数据。

前提条件

获取接入点信息

新版控制台

  1. 登录可观测链路 OpenTelemetry 版控制台,在左侧导航栏单击接入中心

  2. 开源框架区域单击OpenTelemetry卡片。

  3. 在弹出的OpenTelemetry面板中选择数据需要上报的地域。

    说明

    初次接入的地域将会自动进行资源初始化。

  4. 选择连接方式上报方式,然后复制接入点信息。

    • 连接方式:若您的服务部署在阿里云上,且所属地域与选择的接入地域一致,推荐使用阿里云内网方式,否则选择公网方式。

    • 上报方式:根据客户端支持的协议类型选择HTTP或gRPC协议上报数据。

    image.png

旧版控制台

  1. 登录可观测链路 OpenTelemetry 版控制台

  2. 在左侧导航栏单击集群配置,然后在右侧页面单击接入点信息页签。

  3. 在页面顶部选择需要接入的地域,然后在集群信息区域打开显示Token开关。

  4. 客户端采集工具区域单击OpenTelemetry

    相关信息列中,获取接入点信息。ot旧版中.jpg

    说明

    如果应用部署于阿里云生产环境,则选择阿里云VPC网络接入点,否则选择公网接入点。

示例Demo

示例代码仓库地址:opentelemetry-cpp-demo

环境要求

步骤一:环境准备

  1. (可选)运行C++镜像。

    docker pull gcc # 这个镜像用的系统是debian
    docker run -it --name otel-cpp-demo gcc bash
  2. 安装必备的依赖。

    • protobuf

    • grpc

    apt-get update
    apt-get install sudo
    
    sudo apt-get install git cmake g++ libcurl4-openssl-dev
    # 安装 protobuf
    sudo apt-get install protobuf-compiler libprotobuf-dev
    # 安装 grpc
    sudo apt-get install -y libgrpc++-dev libgrpc-dev protobuf-compiler-grpc

步骤二:安装OpenTelemetry C++ Library

git clone --recurse-submodules https://github.com/open-telemetry/opentelemetry-cpp

cd opentelemetry-cpp
mkdir build && cd build
cmake -DBUILD_TESTING=OFF -DWITH_OTLP_GRPC=ON -DWITH_OTLP_HTTP=ON ..

cmake --build . --target all

# 直接安装到/usr/local(推荐)
cmake --install . 

# 或者安装到指定路径
# cmake --install . --prefix /opentelemetry-cpp-lib

步骤三:在项目中使用OpenTelemetry C++ Library

通过HTTP上报数据

  1. 创建项目。

    mkdir otel-http-export-demo
    cd otel otel-http-export-demo
  2. 编写项目CMakeLists.txt文件。

    cmake_minimum_required(VERSION 3.25.1) #version填cmake的版本,cmake --version
    project(otel-http-export-demo) # 括号里填项目名
    
    add_executable(otel-http-export-demo http_exporter.cc) # 项目名和main文件
    
    find_package(opentelemetry-cpp CONFIG REQUIRED)
    find_package(protobuf)
    find_package(gRPC)
    find_package(CURL)
    find_package(nlohmann_json)
    
    include_directories("${OPENTELEMETRY_CPP_INCLUDE_DIRS}")
    
    target_link_libraries(
        opentelemetry_trace
        opentelemetry_common
        opentelemetry_http_client_curl
        opentelemetry_exporter_otlp_http
        opentelemetry_exporter_otlp_grpc
        opentelemetry_exporter_otlp_http_client
        opentelemetry_otlp_recordable
        opentelemetry_resources
    )
  3. 编写Demo。

    测试代码只包含一个http_exporter.cc文件。

    请将${ServiceName}替换为您的应用名,将${HostName}替换为主机名。

    // Copyright The OpenTelemetry Authors
    // SPDX-License-Identifier: Apache-2.0
    
    #include "opentelemetry/exporters/otlp/otlp_http_exporter_factory.h"
    #include "opentelemetry/exporters/otlp/otlp_http_exporter_options.h"
    #include "opentelemetry/context/propagation/global_propagator.h"
    #include "opentelemetry/context/propagation/text_map_propagator.h"
    #include "opentelemetry/exporters/ostream/span_exporter_factory.h"
    #include "opentelemetry/nostd/shared_ptr.h"
    #include "opentelemetry/sdk/trace/simple_processor_factory.h"
    #include "opentelemetry/sdk/trace/tracer_context.h"
    #include "opentelemetry/sdk/trace/tracer_context_factory.h"
    #include "opentelemetry/sdk/trace/tracer_provider_factory.h"
    #include "opentelemetry/trace/propagation/http_trace_context.h"
    #include "opentelemetry/trace/provider.h"
    #include "opentelemetry/ext/http/client/http_client_factory.h"
    #include "opentelemetry/sdk/resource/semantic_conventions.h"
    #include "opentelemetry/sdk/common/global_log_handler.h"
    
    #include <string>
    
    
    namespace trace     = opentelemetry::trace;
    namespace trace_sdk = opentelemetry::sdk::trace;
    namespace otlp      = opentelemetry::exporter::otlp;
    namespace internal_log = opentelemetry::sdk::common::internal_log;
    namespace resource = opentelemetry::sdk::resource;
    
    namespace nostd = opentelemetry::nostd;
    
    namespace
    {
        opentelemetry::exporter::otlp::OtlpHttpExporterOptions opts;
        void InitTracer()
        {
            // 创建OTLP exporter
            auto exporter  = otlp::OtlpHttpExporterFactory::Create(opts);
            auto processor = trace_sdk::SimpleSpanProcessorFactory::Create(std::move(exporter));
    
            resource::ResourceAttributes attributes = {
                    {resource::SemanticConventions::kServiceName, "${ServiceName}"}, // 应用名
                    {resource::SemanticConventions::kHostName, "${HostName}"}
            };
            auto resource = opentelemetry::sdk::resource::Resource::Create(attributes);
    
            std::shared_ptr<opentelemetry::trace::TracerProvider> provider =
                    trace_sdk::TracerProviderFactory::Create(std::move(processor), std::move(resource));
    
            // 设置Trace provider
            trace::Provider::SetTracerProvider(provider);
        }
    
        void CleanupTracer()
        {
            std::shared_ptr<opentelemetry::trace::TracerProvider> none;
            trace::Provider::SetTracerProvider(none);
        }
    
        nostd::shared_ptr<trace::Tracer> get_tracer()
        {
            auto provider = trace::Provider::GetTracerProvider();
            return provider->GetTracer("library name to trace", OPENTELEMETRY_SDK_VERSION);
        }
    
        void f1()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("f1"));
        }
    
        void f2()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("f2"));
    
            f1();
            f1();
        }
    
        void foo_library()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("library"));
    
            f2();
        }
    }  // namespace
    
    /*
      Usage:
      - example_otlp_http
      - example_otlp_http <URL>
      - example_otlp_http <URL> <DEBUG>
      - example_otlp_http <URL> <DEBUG> <BIN>
      <DEBUG> = yes|no, to turn console debug on or off
      <BIN> = bin, to export in binary format
    */
    int main(int argc, char *argv[])
    {
        if (argc > 1)
        {
            opts.url = argv[1];
            if (argc > 2)
            {
                std::string debug  = argv[2];
                opts.console_debug = debug != "" && debug != "0" && debug != "no";
            }
    
            if (argc > 3)
            {
                std::string binary_mode = argv[3];
                if (binary_mode.size() >= 3 && binary_mode.substr(0, 3) == "bin")
                {
                    opts.content_type = otlp::HttpRequestContentType::kBinary;
                }
            }
        }
    
        if (opts.console_debug)
        {
            internal_log::GlobalLogHandler::SetLogLevel(internal_log::LogLevel::Debug);
        }
    
        InitTracer();
    
        foo_library();
    
        CleanupTracer();
    }
  4. 编译项目。

    mkdir build && cd build && cmake .. && make
  5. 运行项目。

    ./otel-http-export-demo ${http-endpoint}

    请将${http-endpoint}替换为前提条件中获取的HTTP接入点信息。

    例如:

    ./otel-http-export-demo http://tracing-analysis-dc-hz.aliyuncs.com/adapt_xxxxx_xxxxx/api/otlp/traces

通过gRPC上报数据

  1. 创建项目。

    mkdir otel-grpc-export-demo
    cd otel otel-grpc-export-demo
  2. 编写项目CMakeLists.txt文件。

    cmake_minimum_required(VERSION 3.25.1) #version填cmake的版本,cmake --version
    project(otel-grpc-export-demo) # 括号里填项目名
    
    add_executable(otel-grpc-export-demo grpc_exporter.cc) # 项目名和main文件
    
    find_package(opentelemetry-cpp CONFIG REQUIRED)
    find_package(protobuf)
    find_package(gRPC)
    find_package(CURL)
    find_package(nlohmann_json)
    
    include_directories("${OPENTELEMETRY_CPP_INCLUDE_DIRS}")
    
    target_link_libraries(
        otel-grpc-export-demo ${OPENTELEMETRY_CPP_LIBRARIES}
        opentelemetry_trace
        opentelemetry_common
        opentelemetry_http_client_curl
        opentelemetry_exporter_otlp_http
        opentelemetry_exporter_otlp_grpc
        opentelemetry_exporter_otlp_http_client
        opentelemetry_otlp_recordable
        opentelemetry_resources
    )
  3. 编写Demo。

    测试代码只包含一个grpc_exporter.cc文件。

    请将${ServiceName}替换为您的应用名,将${HostName}替换为主机名。

    // Copyright The OpenTelemetry Authors
    // SPDX-License-Identifier: Apache-2.0
    
    #include "opentelemetry/exporters/otlp/otlp_grpc_exporter_factory.h"
    #include "opentelemetry/exporters/otlp/otlp_grpc_exporter_options.h"
    #include "opentelemetry/context/propagation/global_propagator.h"
    #include "opentelemetry/context/propagation/text_map_propagator.h"
    #include "opentelemetry/exporters/ostream/span_exporter_factory.h"
    #include "opentelemetry/nostd/shared_ptr.h"
    #include "opentelemetry/sdk/trace/simple_processor_factory.h"
    #include "opentelemetry/sdk/trace/tracer_context.h"
    #include "opentelemetry/sdk/trace/tracer_context_factory.h"
    #include "opentelemetry/sdk/trace/tracer_provider_factory.h"
    #include "opentelemetry/trace/propagation/http_trace_context.h"
    #include "opentelemetry/trace/provider.h"
    #include "opentelemetry/ext/http/client/http_client_factory.h"
    #include "opentelemetry/sdk/resource/semantic_conventions.h"
    #include "opentelemetry/sdk/common/global_log_handler.h"
    
    #include <string>
    
    
    namespace trace     = opentelemetry::trace;
    namespace trace_sdk = opentelemetry::sdk::trace;
    namespace otlp      = opentelemetry::exporter::otlp;
    namespace internal_log = opentelemetry::sdk::common::internal_log;
    namespace resource = opentelemetry::sdk::resource;
    
    namespace nostd = opentelemetry::nostd;
    
    namespace
    {
        opentelemetry::exporter::otlp::OtlpGrpcExporterOptions opts;
        void InitTracer()
        {
            // 创建OTLP exporter
            auto exporter  = otlp::OtlpGrpcExporterFactory::Create(opts);
            auto processor = trace_sdk::SimpleSpanProcessorFactory::Create(std::move(exporter));
    
            resource::ResourceAttributes attributes = {
                    {resource::SemanticConventions::kServiceName, "${ServiceName} "}, // 应用名
                    {resource::SemanticConventions::kHostName, "${HostName}"}
            };
            auto resource = opentelemetry::sdk::resource::Resource::Create(attributes);
    
            std::shared_ptr<opentelemetry::trace::TracerProvider> provider =
                    trace_sdk::TracerProviderFactory::Create(std::move(processor), std::move(resource));
    
            // 设置Trace provider
            trace::Provider::SetTracerProvider(provider);
        }
    
        void CleanupTracer()
        {
            std::shared_ptr<opentelemetry::trace::TracerProvider> none;
            trace::Provider::SetTracerProvider(none);
        }
    
        nostd::shared_ptr<trace::Tracer> get_tracer()
        {
            auto provider = trace::Provider::GetTracerProvider();
            return provider->GetTracer("library name to trace", OPENTELEMETRY_SDK_VERSION);
        }
    
        void f1()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("f1"));
        }
    
        void f2()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("f2"));
    
            f1();
            f1();
        }
    
        void foo_library()
        {
            auto scoped_span = trace::Scope(get_tracer()->StartSpan("library"));
    
            f2();
        }
    }  // namespace
    
    /*
      Usage:
      - example_otlp_grpc
      - example_otlp_grpc <URL> <TOKEN>
    */
    int main(int argc, char *argv[])
    {
        if (argc > 1)
        {
            opts.endpoint = argv[1];
            if (argc > 2)
            {
                opts.metadata.insert(std::pair<std::string, std::string>("authentication",argv[2]));
            }
    
            if (argc > 3)
            {
                opts.use_ssl_credentials         = true;
                opts.ssl_credentials_cacert_path = argv[3];
            }
        }
    
        InitTracer();
    
        foo_library();
    
        CleanupTracer();
    }
  4. 编译项目。

    mkdir build && cd build && cmake .. && make
  5. 运行项目。

    ./otel-grpc-export-demo ${gRPC-endpoint} ${token}

    请将${gRPC-endpoint}${token}替换为前提条件中获取的gRPC接入点和鉴权Token。

    例如:

    ./otel-grpc-export-demo http://tracing-analysis-dc-hz.aliyuncs.com:8090 xxxxx_xxxxxx

常见报错

运行后提示:

./otel-grpc-export-demo: error while loading shared libraries: libopentelemetry_proto_grpc.so: cannot open shared object file: No such file or directory

执行以下命令修改环境变量。

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/

/usr/local/lib是opentelemetry-cpp安装的地址。

查看监控数据

可观测链路 OpenTelemetry 版控制台应用列表页面选择目标应用,查看链路数据。