In my c++ project I use opentelemetry (v1.14.2) to collect traces and logs. Now I want to add metrics collection using Gauge instrument (double observable gauge) with otlp http/grpc exporter. I've read the official documentation and many other resources and didn't find any gauge usage example.
I tried following code:
void InitMetrics(const std::string& name)
{
opentelemetry::exporter::otlp::OtlpHttpMetricExporterOptions opts;
opts.url = "http://ip:port/v1/metrics";
auto exporter = std::make_unique<otlpexportmetrics::OtlpHttpMetricExporter>(opts);
metric_sdk::PeriodicExportingMetricReaderOptions options;
options.export_interval_millis = std::chrono::milliseconds(1000);
options.export_timeout_millis = std::chrono::milliseconds(500);
std::shared_ptr<metric_sdk::MetricReader> reader{
new metric_sdk::PeriodicExportingMetricReader(std::move(exporter),
options)};
auto provider = std::shared_ptr<metrics_api::MeterProvider>(
new metric_sdk::MeterProvider());
auto p = std::static_pointer_cast<metric_sdk::MeterProvider>(provider);
p->AddMetricReader(std::move(reader));
}
void GaugeExample(const std::string& name)
{
std::string gauge_name = name + "_gauge";
auto meter = metrics_api::Provider::GetMeterProvider()->GetMeter(name+"_meter", "1.0.0", "");
auto gauge = meter->CreateDoubleObservableGauge(gauge_name, "pressure", "MPa");
gauge->AddCallback([](opentelemetry::metrics::ObserverResult res, void* state){
nostd::shared_ptr<opentelemetry::metrics::ObserverResultT<double>> obs;
obs->Observe(5.6, {{"service.name", "example"}});
res.emplace<nostd::shared_ptr<opentelemetry::metrics::ObserverResultT<double>>>(obs);
}, nullptr);
}
int main()
{
InitMetrics("example");
GaugeExample("example");
std::this_thread::sleep_for(std::chrono::seconds(20));
std::shared_ptr<metrics_api::MeterProvider> none;
metrics_api::Provider::SetMeterProvider(none);
return 0;
}
I have SigNoz set up with otlp collector and want to see metrics there (logs and traces exports there well and endpoint is 100% correct) but my metrics don't even go to the otlp collector and I have following warning executing my program:
[Warning] File: /home/user/vcpkg/buildtrees/opentelemetry-cpp/src/v1.14.2-8c1c1d9b6b.clean/sdk/src/metrics/metric_reader.cc:37 MetricReader::Collect invoked while Shutdown in progress!
Could someone give me any working example of Gauge usage?
Gauge metric is observable metric, and it's a bit simular to ObservableCounter, so this may help (observable_counter_example): https://github.com/open-telemetry/opentelemetry-cpp/blob/main/examples/common/metrics_foo_library/foo_library.cc