C++ (OpenTelemetry)
It adds OpenTelemetry to your C++ service and checks that data arrives. How the setup skill works
Instrument a C++ service with the OpenTelemetry C++ SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.
C++ has no agent and no instrumentation libraries for web frameworks, so more of this is your own code than in other languages: you build the three providers, and you create the request span yourself. This guide keeps both in two small headers you can copy. The example server uses cpp-httplib (opens in a new tab). The same span works in any HTTP server that tells you which route matched.
Requirements
- A C++17 compiler and CMake 3.16 or newer. The example is built as C++23, only for
std::stacktrace. - libcurl and Protobuf development packages, which the SDK's OTLP/HTTP exporter needs.
- A Traceway project created with framework OpenTelemetry, and that project's token.
Install
Build the SDK with the OTLP/HTTP exporter and install it under a prefix. The exporter is off by default, so a plain cmake .. builds an SDK that cannot send anything.
git clone --depth 1 --branch v1.30.0 https://github.com/open-telemetry/opentelemetry-cpp.git
cd opentelemetry-cpp
git submodule update --init --depth 1 third_party/opentelemetry-proto third_party/nlohmann-json
cmake -S . -B build \
-DCMAKE_INSTALL_PREFIX=$HOME/otel-cpp \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_POSITION_INDEPENDENT_CODE=ON \
-DOTELCPP_WITH_OTLP_HTTP=ON \
-DOTELCPP_WITH_OTLP_GRPC=OFF \
-DOTELCPP_BUILD_TESTING=OFF \
-DOTELCPP_WITH_EXAMPLES=OFF \
-DOTELCPP_WITH_BENCHMARK=OFF \
-DOTELCPP_WITH_FUNC_TESTS=OFF
cmake --build build -j2
cmake --install buildThe build takes about three minutes on two cores. The option names carry an OTELCPP_ prefix since 1.30.0. Older tutorials use WITH_OTLP_HTTP and friends, which still work in 1.30.0 and print a deprecation warning.
When the system Protobuf is a shared library, the SDK installs libopentelemetry_proto.so as one too. Ship it with your binary, or put the prefix's lib directory on the loader path.
The SDK is also packaged for vcpkg (vcpkg install "opentelemetry-cpp[otlp-http]") and Conan (opentelemetry-cpp on ConanCenter). Those two were not run for this page.
Then link it from your project:
cmake_minimum_required(VERSION 3.16)
project(my-cpp-service CXX)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Threads REQUIRED)
find_package(opentelemetry-cpp CONFIG REQUIRED COMPONENTS api sdk exporters_otlp_http)
add_executable(my-cpp-service main.cpp)
target_link_libraries(
my-cpp-service
PRIVATE opentelemetry-cpp::api
opentelemetry-cpp::sdk
opentelemetry-cpp::otlp_http_exporter
opentelemetry-cpp::otlp_http_log_record_exporter
opentelemetry-cpp::otlp_http_metric_exporter
Threads::Threads
stdc++exp)stdc++exp is only for std::stacktrace with GCC's standard library. Leave it out, and set the standard to 17, if you do not record stack traces.
The example also needs the single header of cpp-httplib next to main.cpp:
curl -L -o httplib.h https://raw.githubusercontent.com/yhirose/cpp-httplib/v0.68.0/httplib.hConfigure
The exporters and the resource read these from the process environment.
export OTEL_SERVICE_NAME=my-cpp-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"OTEL_EXPORTER_OTLP_ENDPOINTtakes the base URL. The exporters append/v1/traces,/v1/metricsand/v1/logsthemselves. Do not end it with a slash: it is not trimmed, and the request goes to//v1/traces.OTEL_SERVICE_NAMEbecomes the Server Name on every endpoint, task and issue. Version travels inOTEL_RESOURCE_ATTRIBUTES. There is noOTEL_SERVICE_VERSIONvariable.- The OTLP/HTTP exporters send protobuf by default, which is what Traceway accepts, so
OTEL_EXPORTER_OTLP_PROTOCOLis not needed.
Two settings that are environment variables in other languages are code in C++: delta temporality for metrics, and the traceparent propagator. Both are in the next file. A failed export is printed on stderr, for example Status:401 for a wrong token, and the process keeps running.
Start the SDK
#pragma once
#include <memory>
#include "opentelemetry/context/propagation/global_propagator.h"
#include "opentelemetry/context/propagation/text_map_propagator.h"
#include "opentelemetry/exporters/otlp/otlp_http_exporter_factory.h"
#include "opentelemetry/exporters/otlp/otlp_http_log_record_exporter_factory.h"
#include "opentelemetry/exporters/otlp/otlp_http_metric_exporter_factory.h"
#include "opentelemetry/exporters/otlp/otlp_http_metric_exporter_options.h"
#include "opentelemetry/logs/provider.h"
#include "opentelemetry/metrics/provider.h"
#include "opentelemetry/sdk/logs/batch_log_record_processor_factory.h"
#include "opentelemetry/sdk/logs/batch_log_record_processor_options.h"
#include "opentelemetry/sdk/logs/logger_provider.h"
#include "opentelemetry/sdk/logs/logger_provider_factory.h"
#include "opentelemetry/sdk/logs/provider.h"
#include "opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader_factory.h"
#include "opentelemetry/sdk/metrics/export/periodic_exporting_metric_reader_options.h"
#include "opentelemetry/sdk/metrics/meter_provider.h"
#include "opentelemetry/sdk/metrics/meter_provider_factory.h"
#include "opentelemetry/sdk/metrics/provider.h"
#include "opentelemetry/sdk/metrics/view/view_registry_factory.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/batch_span_processor_factory.h"
#include "opentelemetry/sdk/trace/batch_span_processor_options.h"
#include "opentelemetry/sdk/trace/provider.h"
#include "opentelemetry/sdk/trace/tracer_provider.h"
#include "opentelemetry/sdk/trace/tracer_provider_factory.h"
#include "opentelemetry/trace/propagation/http_trace_context.h"
#include "opentelemetry/trace/provider.h"
struct Telemetry
{
std::shared_ptr<opentelemetry::sdk::trace::TracerProvider> traces;
std::shared_ptr<opentelemetry::sdk::metrics::MeterProvider> metrics;
std::shared_ptr<opentelemetry::sdk::logs::LoggerProvider> logs;
void shutdown()
{
traces->Shutdown();
logs->Shutdown();
metrics->Shutdown();
}
};
inline Telemetry init_telemetry()
{
namespace otel = opentelemetry;
namespace otlp = opentelemetry::exporter::otlp;
namespace sdk = opentelemetry::sdk;
auto resource = sdk::resource::Resource::Create({});
Telemetry telemetry;
telemetry.traces = sdk::trace::TracerProviderFactory::Create(
sdk::trace::BatchSpanProcessorFactory::Create(otlp::OtlpHttpExporterFactory::Create(),
sdk::trace::BatchSpanProcessorOptions{}),
resource);
sdk::trace::Provider::SetTracerProvider(
std::shared_ptr<otel::trace::TracerProvider>(telemetry.traces));
telemetry.logs = sdk::logs::LoggerProviderFactory::Create(
sdk::logs::BatchLogRecordProcessorFactory::Create(
otlp::OtlpHttpLogRecordExporterFactory::Create(),
sdk::logs::BatchLogRecordProcessorOptions{}),
resource);
sdk::logs::Provider::SetLoggerProvider(
std::shared_ptr<otel::logs::LoggerProvider>(telemetry.logs));
otlp::OtlpHttpMetricExporterOptions metric_options;
metric_options.aggregation_temporality = otlp::PreferredAggregationTemporality::kDelta;
auto reader = sdk::metrics::PeriodicExportingMetricReaderFactory::Create(
otlp::OtlpHttpMetricExporterFactory::Create(metric_options),
sdk::metrics::PeriodicExportingMetricReaderOptions{});
telemetry.metrics =
sdk::metrics::MeterProviderFactory::Create(sdk::metrics::ViewRegistryFactory::Create(),
resource);
telemetry.metrics->AddMetricReader(std::move(reader));
sdk::metrics::Provider::SetMeterProvider(
std::shared_ptr<otel::metrics::MeterProvider>(telemetry.metrics));
otel::context::propagation::GlobalTextMapPropagator::SetGlobalPropagator(
otel::nostd::shared_ptr<otel::context::propagation::TextMapPropagator>(
new otel::trace::propagation::HttpTraceContext()));
return telemetry;
}What is in it besides the three providers:
Resource::Create({})is what readsOTEL_SERVICE_NAMEandOTEL_RESOURCE_ATTRIBUTES.kDeltamakes counters and histograms send what changed since the last export, not the running total. The SDK does not readOTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE.- The propagator. The default one does nothing, so without
SetGlobalPropagatoran incomingtraceparentheader is ignored and traces across services never link. shutdown(). Call it before the process exits. EachShutdown()sends what is still queued. Without it, and after aSIGKILL, the last batch is lost.
Create the Request Span
No library creates this span for you. This header gives every matched route a SERVER span with the attributes Traceway builds an endpoint from, and records exceptions on it:
#pragma once
#include <cstdlib>
#include <exception>
#include <memory>
#include <optional>
#include <stacktrace>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <cxxabi.h>
#include "httplib.h"
#include "opentelemetry/context/propagation/global_propagator.h"
#include "opentelemetry/context/propagation/text_map_propagator.h"
#include "opentelemetry/context/runtime_context.h"
#include "opentelemetry/trace/provider.h"
#include "opentelemetry/trace/scope.h"
#include "opentelemetry/trace/span_startoptions.h"
#include "opentelemetry/trace/tracer.h"
struct TracedError : std::runtime_error
{
using std::runtime_error::runtime_error;
std::stacktrace stack = std::stacktrace::current();
};
class RequestHeaders : public opentelemetry::context::propagation::TextMapCarrier
{
public:
explicit RequestHeaders(const httplib::Headers &headers) : headers_(headers) {}
opentelemetry::nostd::string_view Get(opentelemetry::nostd::string_view key) const noexcept override
{
auto it = headers_.find(std::string(key));
return it == headers_.end() ? opentelemetry::nostd::string_view{}
: opentelemetry::nostd::string_view{it->second};
}
void Set(opentelemetry::nostd::string_view, opentelemetry::nostd::string_view) noexcept override {}
private:
const httplib::Headers &headers_;
};
struct ActiveRequest
{
explicit ActiveRequest(opentelemetry::nostd::shared_ptr<opentelemetry::trace::Span> request_span)
: span(std::move(request_span)), scope(span)
{}
opentelemetry::nostd::shared_ptr<opentelemetry::trace::Span> span;
opentelemetry::trace::Scope scope;
};
inline thread_local std::optional<ActiveRequest> active_request;
inline std::string demangle(const char *mangled)
{
int status = 0;
std::unique_ptr<char, void (*)(void *)> name(
abi::__cxa_demangle(mangled, nullptr, nullptr, &status), std::free);
return status == 0 ? name.get() : mangled;
}
inline void instrument(httplib::Server &server)
{
namespace trace_api = opentelemetry::trace;
namespace context = opentelemetry::context;
server.set_pre_request_handler([](const httplib::Request &req, httplib::Response &) {
auto propagator = context::propagation::GlobalTextMapPropagator::GetGlobalPropagator();
auto current = context::RuntimeContext::GetCurrent();
trace_api::StartSpanOptions options;
options.kind = trace_api::SpanKind::kServer;
options.parent = propagator->Extract(RequestHeaders(req.headers), current);
auto tracer = trace_api::Provider::GetTracerProvider()->GetTracer("http-server");
active_request.emplace(tracer->StartSpan(req.method + " " + req.matched_route,
{{"http.request.method", req.method},
{"http.route", req.matched_route},
{"url.path", req.path}},
options));
return httplib::Server::HandlerResponse::Unhandled;
});
server.set_exception_handler(
[](const httplib::Request &, httplib::Response &res, std::exception_ptr error) {
std::string type = "unknown";
std::string message;
std::string stack;
try
{
std::rethrow_exception(error);
}
catch (const TracedError &e)
{
type = demangle(typeid(e).name());
message = e.what();
stack = std::to_string(e.stack);
}
catch (const std::exception &e)
{
type = demangle(typeid(e).name());
message = e.what();
}
catch (...)
{}
if (active_request)
{
active_request->span->AddEvent("exception", {{"exception.type", type},
{"exception.message", message},
{"exception.stacktrace", stack}});
}
res.set_content("Internal Server Error\n", "text/plain");
});
server.set_post_routing_handler([](const httplib::Request &, httplib::Response &res) {
if (!active_request)
{
return;
}
active_request->span->SetAttribute("http.response.status_code", res.status);
if (res.status >= 500)
{
active_request->span->SetStatus(trace_api::StatusCode::kError);
}
active_request->span->End();
active_request.reset();
});
}It uses three cpp-httplib hooks, which all run on the worker thread that runs your handler:
- Before the handler, it starts the span with kind
SERVER, the method, the registered route pattern ashttp.routeand the request path. It continues the caller's trace when the request has atraceparentheader, and makes the span the active one, so spans and log records created in the handler belong to it. - When a handler throws, it adds an
exceptionevent with the type and the message. Traceway builds the Issue from that event. - After the handler, it sets the status code, marks a 5xx as failed and ends the span.
A request that matches no route gets no span.
Instrument the Server
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>
#include <signal.h>
#include <unistd.h>
#include "http_server_span.h"
#include "telemetry.h"
#include "opentelemetry/logs/logger.h"
#include "opentelemetry/metrics/sync_instruments.h"
#include "opentelemetry/trace/context.h"
#include "opentelemetry/trace/span_metadata.h"
namespace otel = opentelemetry;
namespace trace_api = opentelemetry::trace;
int main()
{
sigset_t signals;
sigemptyset(&signals);
sigaddset(&signals, SIGINT);
sigaddset(&signals, SIGTERM);
pthread_sigmask(SIG_BLOCK, &signals, nullptr);
Telemetry telemetry = init_telemetry();
auto tracer = trace_api::Provider::GetTracerProvider()->GetTracer("my-cpp-service", "1.0.0");
auto logger = otel::logs::Provider::GetLoggerProvider()->GetLogger("my-cpp-service");
auto meter = otel::metrics::Provider::GetMeterProvider()->GetMeter("my-cpp-service", "1.0.0");
auto sessions_cleaned = meter->CreateUInt64Counter(
"app.sessions_cleaned", "Expired sessions removed by the cleanup job", "{session}");
httplib::Server server;
instrument(server);
server.Get("/users/:id", [&](const httplib::Request &req, httplib::Response &res) {
const std::string id = req.path_params.at("id");
logger->Info("looking up user " + id);
auto span = tracer->StartSpan("load-user", {{"user.id", id}});
{
auto scope = trace_api::Tracer::WithActiveSpan(span);
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
span->End();
res.set_content("{\"id\":\"" + id + "\",\"name\":\"User " + id + "\"}", "application/json");
});
server.Get("/boom", [](const httplib::Request &, httplib::Response &) {
throw TracedError("boom: something went wrong");
});
server.Get("/run-job", [&](const httplib::Request &, httplib::Response &res) {
trace_api::StartSpanOptions options;
options.kind = trace_api::SpanKind::kConsumer;
options.parent = otel::context::Context{trace_api::kIsRootSpanKey, true};
auto span = tracer->StartSpan("cleanup-expired-sessions", options);
{
auto scope = trace_api::Tracer::WithActiveSpan(span);
sessions_cleaned->Add(7, {{"job", "cleanup-expired-sessions"}});
}
span->End();
res.set_content("{\"cleaned\":7}", "application/json");
});
std::thread stopper([&] {
int signal = 0;
server.wait_until_ready();
sigwait(&signals, &signal);
server.stop();
});
const int port = std::atoi(std::getenv("PORT") ? std::getenv("PORT") : "8080");
std::cout << "listening on http://localhost:" << port << std::endl;
const bool served = server.listen("0.0.0.0", port);
if (!served)
{
std::cerr << "cannot listen on port " << port << std::endl;
kill(getpid(), SIGTERM);
}
stopper.join();
telemetry.shutdown();
return served ? 0 : 1;
}Build and run it with the variables from Configure set:
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_PREFIX_PATH=$HOME/otel-cpp
cmake --build build
PORT=8080 ./build/my-cpp-serviceserver.Get("/users/:id", ...) becomes the endpoint GET /users/:id.
Exceptions and Stack Traces
A caught C++ exception does not know where it was thrown, so an Issue has a stack trace only if you capture one. TracedError in http_server_span.h does it in standard C++23: it takes std::stacktrace::current() when it is constructed, and the exception handler sends it as exception.stacktrace.
throw TracedError("boom: something went wrong");Build with debug information (RelWithDebInfo or -g) to get file names and line numbers in the frames.
An exception of any other type is still recorded, with its type and message and no stack. Know what that means for grouping: Traceway groups Issues by type and stack, so without a stack every std::runtime_error in your service is one Issue, whatever its message. Throw TracedError, or your own classes derived from it, where you want separate Issues.
Logs
Log through the OpenTelemetry logs API. A record written while a span is active takes that span's trace id and span id by itself:
auto logger = opentelemetry::logs::Provider::GetLoggerProvider()->GetLogger("my-cpp-service");
logger->Info("looking up user " + id);If you already log with spdlog, Boost.Log, glog or log4cxx, the opentelemetry-cpp-contrib (opens in a new tab) repository has bridges for them. They were not run for this page.
Background Tasks
A job appears under Tasks when its span has kind CONSUMER. A root span with the default kind is dropped.
trace_api::StartSpanOptions options;
options.kind = trace_api::SpanKind::kConsumer;
options.parent = otel::context::Context{trace_api::kIsRootSpanKey, true};
auto span = tracer->StartSpan("cleanup-expired-sessions", options);The span name is the task name, so keep it stable and put job ids and batch sizes in attributes. The kIsRootSpanKey parent makes the job the root of its own trace. It matters when the job is started from inside a request, as in this example. End the span yourself with span->End().
Custom Metrics
auto meter = opentelemetry::metrics::Provider::GetMeterProvider()->GetMeter("my-cpp-service", "1.0.0");
auto sessions_cleaned = meter->CreateUInt64Counter("app.sessions_cleaned");
sessions_cleaned->Add(7, {{"job", "cleanup-expired-sessions"}});The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. Nothing in this setup records http.server.* metrics, so there is nothing to switch off.
Metrics export every 60 seconds by default. To shorten that while you are checking the integration, set both of these, and remove them afterwards:
export OTEL_METRIC_EXPORT_INTERVAL=5000
export OTEL_METRIC_EXPORT_TIMEOUT=4000The reader rejects an interval that is not longer than its timeout, which defaults to 30 seconds. With only the first variable it prints one warning and stays at 60 seconds.
Verify It Worked
Start the service, then send a few requests:
curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-jobSet the dashboard time picker to the last 15 minutes and check:
- Endpoints. One row
GET /users/:idwith a count of 3, andGET /boomwith status 500. - Issues.
TracedError: boom: something went wrongwith its stack trace. - Logs. Three
looking up userlines, each linked to its trace. - Tasks.
cleanup-expired-sessions. - Metrics.
app.sessions_cleanedin metric discovery.
Nothing at all? Read the service's stderr: export failures are printed there.