diff --git a/src/lib/metrics/metrics.cpp b/src/lib/metrics/metrics.cpp index 3e57d86fc43..77a4bb8b3a8 100644 --- a/src/lib/metrics/metrics.cpp +++ b/src/lib/metrics/metrics.cpp @@ -17,6 +17,10 @@ Metrics &Metrics::getInstance() { } void Metrics::init(Options opts) { + if (!opts.enableOStreamExporter && !opts.enablePrometheusExporter) { + return; + } + auto provider = metrics_sdk::MeterProviderFactory::Create(); auto* p = static_cast(provider.get()); @@ -69,12 +73,7 @@ void Metrics::init(Options opts) { latencyHistograms[name] = getMeter()->CreateDoubleHistogram(name, "Latency", "us"); } - if (opts.enableOStreamExporter || opts.enablePrometheusExporter) { - metrics_api::Provider::SetMeterProvider(std::move(provider)); - } else { - std::shared_ptr none; - metrics_api::Provider::SetMeterProvider(none); - } + metrics_api::Provider::SetMeterProvider(std::move(provider)); } void Metrics::shutdown() { @@ -85,7 +84,6 @@ void Metrics::shutdown() { ScopedLatency::ScopedLatency(std::string_view name, const std::string &histogramName, const std::string &scopeKey) : ScopedLatency(name, g_metrics().latencyHistograms[histogramName], { { scopeKey, std::string(name) } }, g_metrics().defaultContext) { if (histogram == nullptr) { - g_logger().debug("ScopedLatency: Histogram {} not found", histogramName); stopped = true; return; } diff --git a/src/lib/metrics/metrics.hpp b/src/lib/metrics/metrics.hpp index de3ac999ab1..116676fb3b7 100644 --- a/src/lib/metrics/metrics.hpp +++ b/src/lib/metrics/metrics.hpp @@ -118,6 +118,9 @@ namespace metrics { void addCounter(std::string_view name, double value, std::map attrs = {}) { std::scoped_lock lock(mutex_); + if (!getMeter()) { + return; + } if (counters.find(name) == counters.end()) { std::string nameStr(name); counters[name] = getMeter()->CreateDoubleCounter(nameStr); @@ -128,6 +131,9 @@ namespace metrics { void addUpDownCounter(std::string_view name, int value, std::map attrs = {}) { std::scoped_lock lock(mutex_); + if (!getMeter()) { + return; + } if (upDownCounters.find(name) == upDownCounters.end()) { std::string nameStr(name); upDownCounters[name] = getMeter()->CreateInt64UpDownCounter(nameStr); @@ -145,7 +151,11 @@ namespace metrics { phmap::flat_hash_map> counters; Meter getMeter() { - return metrics_api::Provider::GetMeterProvider()->GetMeter(meterName, otelVersion); + auto provider = metrics_api::Provider::GetMeterProvider(); + if (provider == nullptr) { + return {}; + } + return provider->GetMeter(meterName, otelVersion); } private: