opentelemetry/global/
metrics.rsuse crate::metrics::{self, Meter, MeterProvider};
use crate::{otel_error, otel_info, InstrumentationScope};
use std::sync::{Arc, OnceLock, RwLock};
type GlobalMeterProvider = Arc<dyn MeterProvider + Send + Sync>;
static GLOBAL_METER_PROVIDER: OnceLock<RwLock<GlobalMeterProvider>> = OnceLock::new();
#[inline]
fn global_meter_provider() -> &'static RwLock<GlobalMeterProvider> {
GLOBAL_METER_PROVIDER
.get_or_init(|| RwLock::new(Arc::new(crate::metrics::noop::NoopMeterProvider::new())))
}
pub fn set_meter_provider<P>(new_provider: P)
where
P: metrics::MeterProvider + Send + Sync + 'static,
{
let mut global_provider = global_meter_provider().write();
if let Ok(ref mut provider) = global_provider {
**provider = Arc::new(new_provider);
otel_info!(name: "MeterProvider.GlobalSet", message = "Global meter provider is set. Meters can now be created using global::meter() or global::meter_with_scope().");
} else {
otel_error!(name: "MeterProvider.GlobalSetFailed", message = "Setting global meter provider failed. Meters created using global::meter() or global::meter_with_scope() will not function. Report this issue in OpenTelemetry repo.");
}
}
pub fn meter_provider() -> GlobalMeterProvider {
let global_provider = global_meter_provider().read();
if let Ok(provider) = global_provider {
provider.clone()
} else {
otel_error!(name: "MeterProvider.GlobalGetFailed", message = "Getting global meter provider failed. Meters created using global::meter() or global::meter_with_scope() will not function. Report this issue in OpenTelemetry repo.");
Arc::new(crate::metrics::noop::NoopMeterProvider::new())
}
}
pub fn meter(name: &'static str) -> Meter {
meter_provider().meter(name)
}
pub fn meter_with_scope(scope: InstrumentationScope) -> Meter {
meter_provider().meter_with_scope(scope)
}