了解如何使用 OpenTelemetry 编译和运行 C++ 示例,并将跟踪记录导出到 Cloud Trace。此示例使用 Google Cloud Pub/Sub C++ 客户端发布了 5 条消息,并将跟踪记录导出到 Cloud Trace。
准备工作
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
// Create a few namespace aliases to make the code easier to read.namespacegc=::google::cloud;namespaceotel=gc::otel;namespacepubsub=gc::pubsub;// This example uses a simple wrapper to export (upload) OTel tracing data// to Google Cloud Trace. More complex applications may use different// authentication, or configure their own OTel exporter.autoproject=gc::Project(project_id);autoconfiguration=otel::ConfigureBasicTracing(project);autopublisher=pubsub::Publisher(pubsub::MakePublisherConnection(pubsub::Topic(project_id,topic_id),// Configure this publisher to enable OTel tracing. Some applications may// chose to disable tracing in some publishers or to dynamically enable// this option based on their own configuration.gc::Options{}.set<gc::OpenTelemetryTracingOption>(true)));// After this point, use the Cloud Pub/Sub C++ client library as usual.// In this example, we will send a few messages and configure a callback// action for each one.std::vector<gc::future<void>>ids;for(inti=0;i < 5;i++){autoid=publisher.Publish(pubsub::MessageBuilder().SetData("Hi!").Build()).then([](gc::future<gc::StatusOr<std::string>>f){autoid=f.get();if(!id){std::cout << "Error in publish: " << id.status() << "\n";return;}std::cout << "Sent message with id: (" << *id << ")\n";});ids.push_back(std::move(id));}// Block until the messages are actually sent.for(auto&id:ids)id.get();
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-03-10。"],[[["This guide demonstrates how to compile and run a C++ application that utilizes OpenTelemetry for tracing and exports the trace data to Google Cloud Trace."],["The example publishes five messages using the Google Cloud Pub/Sub C++ client, with OpenTelemetry tracing enabled for the publisher."],["Before running the example, a Pub/Sub topic named `my-topic` must be created, and the C++ sample source code should be cloned."],["After compiling and running the example, trace data can be viewed in the Google Cloud Console's Trace explorer page, and the `my-topic` created can be deleted to clean up resources."]]],[]]