diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 930bf727c3..eb6a38ca80 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -140,7 +140,7 @@ For a deeper discussion, see: Currently, the Opentelemetry Rust SDK has two ways to handle errors. In the situation where errors are not allowed to return. One should call global error handler to process the errors. Otherwise, one should return the errors. -The Opentelemetry Rust SDK comes with an error type `opentelemetry::Error`. For different function, one error has been defined. All error returned by trace module MUST be wrapped in `opentelemetry::trace::TraceError`. All errors returned by metrics module MUST be wrapped in `opentelemetry::metrics::MetricsError`. All errors returned by logs module MUST be wrapped in `opentelemetry::logs::LogsError`. +The Opentelemetry Rust SDK comes with an error type `opentelemetry::Error`. For different function, one error has been defined. All error returned by trace module MUST be wrapped in `opentelemetry::trace::TraceError`. All errors returned by metrics module MUST be wrapped in `opentelemetry::metrics::MetricError`. All errors returned by logs module MUST be wrapped in `opentelemetry::logs::LogsError`. For users that want to implement their own exporters. It's RECOMMENDED to wrap all errors from the exporter into a crate-level error type, and implement `ExporterError` trait. diff --git a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs index 029efaaa30..916bd713df 100644 --- a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs +++ b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs @@ -1,7 +1,7 @@ use once_cell::sync::Lazy; use opentelemetry::{ global, - metrics::MetricsError, + metrics::MetricError, trace::{TraceContextExt, TraceError, Tracer}, InstrumentationScope, KeyValue, }; @@ -65,7 +65,7 @@ fn init_tracer_provider() -> Result { .build()) } -fn init_metrics() -> Result { +fn init_metrics() -> Result { let exporter = MetricsExporter::builder() .with_http() .with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format diff --git a/opentelemetry-otlp/examples/basic-otlp/src/main.rs b/opentelemetry-otlp/examples/basic-otlp/src/main.rs index 60f2922a35..979eaf36f3 100644 --- a/opentelemetry-otlp/examples/basic-otlp/src/main.rs +++ b/opentelemetry-otlp/examples/basic-otlp/src/main.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use opentelemetry::logs::LogError; -use opentelemetry::metrics::MetricsError; +use opentelemetry::metrics::MetricError; use opentelemetry::trace::{TraceContextExt, TraceError, Tracer}; use opentelemetry::KeyValue; use opentelemetry::{global, InstrumentationScope}; @@ -33,7 +33,7 @@ fn init_tracer_provider() -> Result { .build()) } -fn init_metrics() -> Result { +fn init_metrics() -> Result { let exporter = MetricsExporter::builder().with_tonic().build()?; let reader = PeriodicReader::builder(exporter, runtime::Tokio).build(); diff --git a/opentelemetry-otlp/src/exporter/http/metrics.rs b/opentelemetry-otlp/src/exporter/http/metrics.rs index 8fcf1bc362..b047cd4f32 100644 --- a/opentelemetry-otlp/src/exporter/http/metrics.rs +++ b/opentelemetry-otlp/src/exporter/http/metrics.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use async_trait::async_trait; use http::{header::CONTENT_TYPE, Method}; -use opentelemetry::metrics::{MetricsError, Result}; +use opentelemetry::metrics::{MetricError, MetricResult}; use opentelemetry_sdk::metrics::data::ResourceMetrics; use crate::{metric::MetricsClient, Error}; @@ -11,14 +11,14 @@ use super::OtlpHttpClient; #[async_trait] impl MetricsClient for OtlpHttpClient { - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> { + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> { let client = self .client .lock() .map_err(Into::into) .and_then(|g| match &*g { Some(client) => Ok(Arc::clone(client)), - _ => Err(MetricsError::Other("exporter is already shut down".into())), + _ => Err(MetricError::Other("exporter is already shut down".into())), })?; let (body, content_type) = self.build_metrics_export_body(metrics)?; @@ -36,12 +36,12 @@ impl MetricsClient for OtlpHttpClient { client .send(request) .await - .map_err(|e| MetricsError::ExportErr(Box::new(Error::RequestFailed(e))))?; + .map_err(|e| MetricError::ExportErr(Box::new(Error::RequestFailed(e))))?; Ok(()) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { let _ = self.client.lock()?.take(); Ok(()) diff --git a/opentelemetry-otlp/src/exporter/http/mod.rs b/opentelemetry-otlp/src/exporter/http/mod.rs index 9efd55c56b..b8cd8fe614 100644 --- a/opentelemetry-otlp/src/exporter/http/mod.rs +++ b/opentelemetry-otlp/src/exporter/http/mod.rs @@ -221,7 +221,7 @@ impl HttpExporterBuilder { pub fn build_metrics_exporter( mut self, temporality: opentelemetry_sdk::metrics::data::Temporality, - ) -> opentelemetry::metrics::Result { + ) -> opentelemetry::metrics::MetricResult { use crate::{ OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_HEADERS, OTEL_EXPORTER_OTLP_METRICS_TIMEOUT, @@ -311,7 +311,7 @@ impl OtlpHttpClient { fn build_metrics_export_body( &self, metrics: &mut opentelemetry_sdk::metrics::data::ResourceMetrics, - ) -> opentelemetry::metrics::Result<(Vec, &'static str)> { + ) -> opentelemetry::metrics::MetricResult<(Vec, &'static str)> { use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; let req: ExportMetricsServiceRequest = (&*metrics).into(); @@ -320,7 +320,7 @@ impl OtlpHttpClient { #[cfg(feature = "http-json")] Protocol::HttpJson => match serde_json::to_string_pretty(&req) { Ok(json) => Ok((json.into(), "application/json")), - Err(e) => Err(opentelemetry::metrics::MetricsError::Other(e.to_string())), + Err(e) => Err(opentelemetry::metrics::MetricError::Other(e.to_string())), }, _ => Ok((req.encode_to_vec(), "application/x-protobuf")), } diff --git a/opentelemetry-otlp/src/exporter/tonic/metrics.rs b/opentelemetry-otlp/src/exporter/tonic/metrics.rs index 97040d3201..b8a59858eb 100644 --- a/opentelemetry-otlp/src/exporter/tonic/metrics.rs +++ b/opentelemetry-otlp/src/exporter/tonic/metrics.rs @@ -2,7 +2,7 @@ use core::fmt; use std::sync::Mutex; use async_trait::async_trait; -use opentelemetry::metrics::{MetricsError, Result}; +use opentelemetry::metrics::{MetricError, MetricResult}; use opentelemetry_proto::tonic::collector::metrics::v1::{ metrics_service_client::MetricsServiceClient, ExportMetricsServiceRequest, }; @@ -51,7 +51,7 @@ impl TonicMetricsClient { #[async_trait] impl MetricsClient for TonicMetricsClient { - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> { + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> { let (mut client, metadata, extensions) = self.inner .lock() @@ -62,14 +62,14 @@ impl MetricsClient for TonicMetricsClient { .interceptor .call(Request::new(())) .map_err(|e| { - MetricsError::Other(format!( + MetricError::Other(format!( "unexpected status while exporting {e:?}" )) })? .into_parts(); Ok((inner.client.clone(), m, e)) } - None => Err(MetricsError::Other("exporter is already shut down".into())), + None => Err(MetricError::Other("exporter is already shut down".into())), })?; client @@ -84,7 +84,7 @@ impl MetricsClient for TonicMetricsClient { Ok(()) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { let _ = self.inner.lock()?.take(); Ok(()) diff --git a/opentelemetry-otlp/src/exporter/tonic/mod.rs b/opentelemetry-otlp/src/exporter/tonic/mod.rs index 1c520c80b0..796ab8cc61 100644 --- a/opentelemetry-otlp/src/exporter/tonic/mod.rs +++ b/opentelemetry-otlp/src/exporter/tonic/mod.rs @@ -274,7 +274,7 @@ impl TonicExporterBuilder { pub(crate) fn build_metrics_exporter( self, temporality: opentelemetry_sdk::metrics::data::Temporality, - ) -> opentelemetry::metrics::Result { + ) -> opentelemetry::metrics::MetricResult { use crate::MetricsExporter; use metrics::TonicMetricsClient; diff --git a/opentelemetry-otlp/src/metric.rs b/opentelemetry-otlp/src/metric.rs index 70352e502a..fbd70f52c5 100644 --- a/opentelemetry-otlp/src/metric.rs +++ b/opentelemetry-otlp/src/metric.rs @@ -16,7 +16,7 @@ use crate::NoExporterBuilderSet; use async_trait::async_trait; use core::fmt; -use opentelemetry::metrics::Result; +use opentelemetry::metrics::MetricResult; use opentelemetry_sdk::metrics::{ data::{ResourceMetrics, Temporality}, @@ -77,7 +77,7 @@ impl MetricsExporterBuilder { #[cfg(feature = "grpc-tonic")] impl MetricsExporterBuilder { - pub fn build(self) -> Result { + pub fn build(self) -> MetricResult { let exporter = self.client.0.build_metrics_exporter(self.temporality)?; Ok(exporter) } @@ -85,7 +85,7 @@ impl MetricsExporterBuilder { #[cfg(any(feature = "http-proto", feature = "http-json"))] impl MetricsExporterBuilder { - pub fn build(self) -> Result { + pub fn build(self) -> MetricResult { let exporter = self.client.0.build_metrics_exporter(self.temporality)?; Ok(exporter) } @@ -122,8 +122,8 @@ impl HasHttpConfig for MetricsExporterBuilder { /// An interface for OTLP metrics clients #[async_trait] pub trait MetricsClient: fmt::Debug + Send + Sync + 'static { - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()>; - fn shutdown(&self) -> Result<()>; + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()>; + fn shutdown(&self) -> MetricResult<()>; } /// Export metrics in OTEL format. @@ -140,16 +140,16 @@ impl Debug for MetricsExporter { #[async_trait] impl PushMetricsExporter for MetricsExporter { - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> { + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> { self.client.export(metrics).await } - async fn force_flush(&self) -> Result<()> { + async fn force_flush(&self) -> MetricResult<()> { // this component is stateless Ok(()) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { self.client.shutdown() } diff --git a/opentelemetry-proto/src/transform/metrics.rs b/opentelemetry-proto/src/transform/metrics.rs index f718c96280..66db88a1d4 100644 --- a/opentelemetry-proto/src/transform/metrics.rs +++ b/opentelemetry-proto/src/transform/metrics.rs @@ -8,7 +8,7 @@ pub mod tonic { use std::any::Any; use std::fmt; - use opentelemetry::{global, metrics::MetricsError, Key, Value}; + use opentelemetry::{global, metrics::MetricError, Key, Value}; use opentelemetry_sdk::metrics::data::{ self, Exemplar as SdkExemplar, ExponentialHistogram as SdkExponentialHistogram, Gauge as SdkGauge, Histogram as SdkHistogram, Metric as SdkMetric, @@ -97,7 +97,7 @@ pub mod tonic { Temporality::Cumulative => AggregationTemporality::Cumulative, Temporality::Delta => AggregationTemporality::Delta, other => { - opentelemetry::global::handle_error(MetricsError::Other(format!( + opentelemetry::global::handle_error(MetricError::Other(format!( "Unknown temporality {:?}, using default instead.", other ))); @@ -184,7 +184,7 @@ pub mod tonic { } else if let Some(gauge) = data.downcast_ref::>() { Ok(TonicMetricData::Gauge(gauge.into())) } else { - global::handle_error(MetricsError::Other("unknown aggregator".into())); + global::handle_error(MetricError::Other("unknown aggregator".into())); Err(()) } } diff --git a/opentelemetry-sdk/benches/metric.rs b/opentelemetry-sdk/benches/metric.rs index aaf3e6c017..0e36debb50 100644 --- a/opentelemetry-sdk/benches/metric.rs +++ b/opentelemetry-sdk/benches/metric.rs @@ -3,7 +3,7 @@ use std::sync::{Arc, Weak}; use criterion::{criterion_group, criterion_main, Bencher, Criterion}; use opentelemetry::{ - metrics::{Counter, Histogram, MeterProvider as _, Result}, + metrics::{Counter, Histogram, MeterProvider as _, MetricResult}, Key, KeyValue, }; use opentelemetry_sdk::{ @@ -25,15 +25,15 @@ impl MetricReader for SharedReader { self.0.register_pipeline(pipeline) } - fn collect(&self, rm: &mut ResourceMetrics) -> Result<()> { + fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> { self.0.collect(rm) } - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { self.0.force_flush() } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { self.0.shutdown() } diff --git a/opentelemetry-sdk/src/metrics/aggregation.rs b/opentelemetry-sdk/src/metrics/aggregation.rs index 561aa00c4d..6ccd564870 100644 --- a/opentelemetry-sdk/src/metrics/aggregation.rs +++ b/opentelemetry-sdk/src/metrics/aggregation.rs @@ -1,7 +1,7 @@ use std::fmt; use crate::metrics::internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE}; -use opentelemetry::metrics::{MetricsError, Result}; +use opentelemetry::metrics::{MetricError, MetricResult}; /// The way recorded measurements are summarized. #[derive(Clone, Debug, PartialEq)] @@ -109,7 +109,7 @@ impl fmt::Display for Aggregation { impl Aggregation { /// Validate that this aggregation has correct configuration - pub fn validate(&self) -> Result<()> { + pub fn validate(&self) -> MetricResult<()> { match self { Aggregation::Drop => Ok(()), Aggregation::Default => Ok(()), @@ -118,7 +118,7 @@ impl Aggregation { Aggregation::ExplicitBucketHistogram { boundaries, .. } => { for x in boundaries.windows(2) { if x[0] >= x[1] { - return Err(MetricsError::Config(format!( + return Err(MetricError::Config(format!( "aggregation: explicit bucket histogram: non-monotonic boundaries: {:?}", boundaries, ))); @@ -129,13 +129,13 @@ impl Aggregation { } Aggregation::Base2ExponentialHistogram { max_scale, .. } => { if *max_scale > EXPO_MAX_SCALE { - return Err(MetricsError::Config(format!( + return Err(MetricError::Config(format!( "aggregation: exponential histogram: max scale ({}) is greater than 20", max_scale, ))); } if *max_scale < EXPO_MIN_SCALE { - return Err(MetricsError::Config(format!( + return Err(MetricError::Config(format!( "aggregation: exponential histogram: max scale ({}) is less than -10", max_scale, ))); @@ -153,17 +153,17 @@ mod tests { internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE}, Aggregation, }; - use opentelemetry::metrics::{MetricsError, Result}; + use opentelemetry::metrics::{MetricError, MetricResult}; #[test] fn validate_aggregation() { struct TestCase { name: &'static str, input: Aggregation, - check: Box) -> bool>, + check: Box) -> bool>, } - let ok = Box::new(|result: Result<()>| result.is_ok()); - let config_error = Box::new(|result| matches!(result, Err(MetricsError::Config(_)))); + let ok = Box::new(|result: MetricResult<()>| result.is_ok()); + let config_error = Box::new(|result| matches!(result, Err(MetricError::Config(_)))); let test_cases: Vec = vec![ TestCase { diff --git a/opentelemetry-sdk/src/metrics/exporter.rs b/opentelemetry-sdk/src/metrics/exporter.rs index ff7d9fb593..39802dd07c 100644 --- a/opentelemetry-sdk/src/metrics/exporter.rs +++ b/opentelemetry-sdk/src/metrics/exporter.rs @@ -1,7 +1,7 @@ //! Interfaces for exporting metrics use async_trait::async_trait; -use opentelemetry::metrics::Result; +use opentelemetry::metrics::MetricResult; use crate::metrics::data::ResourceMetrics; @@ -18,16 +18,16 @@ pub trait PushMetricsExporter: Send + Sync + 'static { /// implement any retry logic. All errors returned by this function are /// considered unrecoverable and will be reported to a configured error /// Handler. - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()>; + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()>; /// Flushes any metric data held by an exporter. - async fn force_flush(&self) -> Result<()>; + async fn force_flush(&self) -> MetricResult<()>; /// Releases any held computational resources. /// /// After Shutdown is called, calls to Export will perform no operation and /// instead will return an error indicating the shutdown state. - fn shutdown(&self) -> Result<()>; + fn shutdown(&self) -> MetricResult<()>; /// Access the [Temporality] of the MetricsExporter. fn temporality(&self) -> Temporality; diff --git a/opentelemetry-sdk/src/metrics/internal/mod.rs b/opentelemetry-sdk/src/metrics/internal/mod.rs index 7a79fe4653..84547d80a6 100644 --- a/opentelemetry-sdk/src/metrics/internal/mod.rs +++ b/opentelemetry-sdk/src/metrics/internal/mod.rs @@ -16,7 +16,7 @@ use aggregate::is_under_cardinality_limit; pub(crate) use aggregate::{AggregateBuilder, ComputeAggregation, Measure}; pub(crate) use exponential_histogram::{EXPO_MAX_SCALE, EXPO_MIN_SCALE}; use once_cell::sync::Lazy; -use opentelemetry::metrics::MetricsError; +use opentelemetry::metrics::MetricError; use opentelemetry::{global, otel_warn, KeyValue}; use crate::metrics::AttributeSet; @@ -146,7 +146,7 @@ impl, T: Number, O: Operation> ValueMap { let new_tracker = AU::new_atomic_tracker(self.buckets_count); O::update_tracker(&new_tracker, measurement, index); trackers.insert(STREAM_OVERFLOW_ATTRIBUTES.clone(), Arc::new(new_tracker)); - global::handle_error(MetricsError::Other("Warning: Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged.".into())); + global::handle_error(MetricError::Other("Warning: Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged.".into())); otel_warn!( name: "ValueMap.measure", message = "Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged." ); diff --git a/opentelemetry-sdk/src/metrics/manual_reader.rs b/opentelemetry-sdk/src/metrics/manual_reader.rs index b79b1d7ae7..f64c61b91d 100644 --- a/opentelemetry-sdk/src/metrics/manual_reader.rs +++ b/opentelemetry-sdk/src/metrics/manual_reader.rs @@ -4,7 +4,7 @@ use std::{ }; use opentelemetry::{ - metrics::{MetricsError, Result}, + metrics::{MetricError, MetricResult}, otel_debug, }; @@ -88,12 +88,12 @@ impl MetricReader for ManualReader { /// callbacks necessary and returning the results. /// /// Returns an error if called after shutdown. - fn collect(&self, rm: &mut ResourceMetrics) -> Result<()> { + fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> { let inner = self.inner.lock()?; match &inner.sdk_producer.as_ref().and_then(|w| w.upgrade()) { Some(producer) => producer.produce(rm)?, None => { - return Err(MetricsError::Other( + return Err(MetricError::Other( "reader is shut down or not registered".into(), )) } @@ -103,12 +103,12 @@ impl MetricReader for ManualReader { } /// ForceFlush is a no-op, it always returns nil. - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { Ok(()) } /// Closes any connections and frees any resources used by the reader. - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { let mut inner = self.inner.lock()?; // Any future call to collect will now return an error. diff --git a/opentelemetry-sdk/src/metrics/meter.rs b/opentelemetry-sdk/src/metrics/meter.rs index 1a5432f000..d0647709e0 100644 --- a/opentelemetry-sdk/src/metrics/meter.rs +++ b/opentelemetry-sdk/src/metrics/meter.rs @@ -5,8 +5,8 @@ use opentelemetry::{ global, metrics::{ AsyncInstrumentBuilder, Counter, Gauge, Histogram, HistogramBuilder, InstrumentBuilder, - InstrumentProvider, MetricsError, ObservableCounter, ObservableGauge, - ObservableUpDownCounter, Result, UpDownCounter, + InstrumentProvider, MetricError, MetricResult, ObservableCounter, ObservableGauge, + ObservableUpDownCounter, UpDownCounter, }, otel_error, InstrumentationScope, }; @@ -493,45 +493,45 @@ impl InstrumentProvider for SdkMeter { } } -fn validate_instrument_config(name: &str, unit: &Option>) -> Result<()> { +fn validate_instrument_config(name: &str, unit: &Option>) -> MetricResult<()> { validate_instrument_name(name).and_then(|_| validate_instrument_unit(unit)) } -fn validate_instrument_name(name: &str) -> Result<()> { +fn validate_instrument_name(name: &str) -> MetricResult<()> { if name.is_empty() { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_NAME_EMPTY, )); } if name.len() > INSTRUMENT_NAME_MAX_LENGTH { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_NAME_LENGTH, )); } if name.starts_with(|c: char| !c.is_ascii_alphabetic()) { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_NAME_FIRST_ALPHABETIC, )); } if name.contains(|c: char| { !c.is_ascii_alphanumeric() && !INSTRUMENT_NAME_ALLOWED_NON_ALPHANUMERIC_CHARS.contains(&c) }) { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_NAME_INVALID_CHAR, )); } Ok(()) } -fn validate_instrument_unit(unit: &Option>) -> Result<()> { +fn validate_instrument_unit(unit: &Option>) -> MetricResult<()> { if let Some(unit) = unit { if unit.len() > INSTRUMENT_UNIT_NAME_MAX_LENGTH { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_UNIT_LENGTH, )); } if unit.contains(|c: char| !c.is_ascii()) { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( INSTRUMENT_UNIT_INVALID_CHAR, )); } @@ -567,7 +567,7 @@ where description: Option>, unit: Option>, boundaries: Option>, - ) -> Result> { + ) -> MetricResult> { let aggregators = self.measures(kind, name, description, unit, boundaries)?; Ok(ResolvedMeasures { measures: aggregators, @@ -581,7 +581,7 @@ where description: Option>, unit: Option>, boundaries: Option>, - ) -> Result>>> { + ) -> MetricResult>>> { let inst = Instrument { name, description: description.unwrap_or_default(), @@ -598,7 +598,7 @@ where mod tests { use std::borrow::Cow; - use opentelemetry::metrics::MetricsError; + use opentelemetry::metrics::MetricError; use super::{ validate_instrument_name, validate_instrument_unit, INSTRUMENT_NAME_FIRST_ALPHABETIC, @@ -621,13 +621,13 @@ mod tests { ("allow.dots.ok", ""), ]; for (name, expected_error) in instrument_name_test_cases { - let assert = |result: Result<_, MetricsError>| { + let assert = |result: Result<_, MetricError>| { if expected_error.is_empty() { assert!(result.is_ok()); } else { assert!(matches!( result.unwrap_err(), - MetricsError::InvalidInstrumentConfiguration(msg) if msg == expected_error + MetricError::InvalidInstrumentConfiguration(msg) if msg == expected_error )); } }; @@ -652,13 +652,13 @@ mod tests { ]; for (unit, expected_error) in instrument_unit_test_cases { - let assert = |result: Result<_, MetricsError>| { + let assert = |result: Result<_, MetricError>| { if expected_error.is_empty() { assert!(result.is_ok()); } else { assert!(matches!( result.unwrap_err(), - MetricsError::InvalidInstrumentConfiguration(msg) if msg == expected_error + MetricError::InvalidInstrumentConfiguration(msg) if msg == expected_error )); } }; diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs index 2450328401..4c53e8d12e 100644 --- a/opentelemetry-sdk/src/metrics/meter_provider.rs +++ b/opentelemetry-sdk/src/metrics/meter_provider.rs @@ -8,7 +8,7 @@ use std::{ }; use opentelemetry::{ - metrics::{Meter, MeterProvider, MetricsError, Result}, + metrics::{Meter, MeterProvider, MetricError, MetricResult}, otel_debug, otel_error, InstrumentationScope, }; @@ -91,7 +91,7 @@ impl SdkMeterProvider { /// Ok(()) /// } /// ``` - pub fn force_flush(&self) -> Result<()> { + pub fn force_flush(&self) -> MetricResult<()> { self.inner.force_flush() } @@ -107,17 +107,17 @@ impl SdkMeterProvider { /// /// There is no guaranteed that all telemetry be flushed or all resources have /// been released on error. - pub fn shutdown(&self) -> Result<()> { + pub fn shutdown(&self) -> MetricResult<()> { self.inner.shutdown() } } impl SdkMeterProviderInner { - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { self.pipes.force_flush() } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { if self .is_shutdown .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -125,7 +125,7 @@ impl SdkMeterProviderInner { { self.pipes.shutdown() } else { - Err(MetricsError::Other( + Err(MetricError::Other( "metrics provider already shut down".into(), )) } diff --git a/opentelemetry-sdk/src/metrics/periodic_reader.rs b/opentelemetry-sdk/src/metrics/periodic_reader.rs index bebac2cff5..0fcea11252 100644 --- a/opentelemetry-sdk/src/metrics/periodic_reader.rs +++ b/opentelemetry-sdk/src/metrics/periodic_reader.rs @@ -12,7 +12,7 @@ use futures_util::{ StreamExt, }; use opentelemetry::{ - metrics::{MetricsError, Result}, + metrics::{MetricError, MetricResult}, otel_debug, otel_error, }; @@ -211,8 +211,8 @@ struct PeriodicReaderInner { #[derive(Debug)] enum Message { Export, - Flush(oneshot::Sender>), - Shutdown(oneshot::Sender>), + Flush(oneshot::Sender>), + Shutdown(oneshot::Sender>), } enum ProducerOrWorker { @@ -228,7 +228,7 @@ struct PeriodicReaderWorker { } impl PeriodicReaderWorker { - async fn collect_and_export(&mut self) -> Result<()> { + async fn collect_and_export(&mut self) -> MetricResult<()> { self.reader.collect(&mut self.rm)?; if self.rm.scope_metrics.is_empty() { // No metrics to export. @@ -244,7 +244,7 @@ impl PeriodicReaderWorker { Either::Left((res, _)) => { res // return the status of export. } - Either::Right(_) => Err(MetricsError::Other("export timed out".into())), + Either::Right(_) => Err(MetricError::Other("export timed out".into())), } } @@ -315,10 +315,10 @@ impl MetricReader for PeriodicReader { worker(self); } - fn collect(&self, rm: &mut ResourceMetrics) -> Result<()> { + fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> { let inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is shut down".into())); + return Err(MetricError::Other("reader is shut down".into())); } if let Some(producer) = match &inner.sdk_producer_or_worker { @@ -327,45 +327,45 @@ impl MetricReader for PeriodicReader { } { producer.produce(rm)?; } else { - return Err(MetricsError::Other("reader is not registered".into())); + return Err(MetricError::Other("reader is not registered".into())); } Ok(()) } - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { let mut inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is shut down".into())); + return Err(MetricError::Other("reader is shut down".into())); } let (sender, receiver) = oneshot::channel(); inner .message_sender .try_send(Message::Flush(sender)) - .map_err(|e| MetricsError::Other(e.to_string()))?; + .map_err(|e| MetricError::Other(e.to_string()))?; drop(inner); // don't hold lock when blocking on future futures_executor::block_on(receiver) - .map_err(|err| MetricsError::Other(err.to_string())) + .map_err(|err| MetricError::Other(err.to_string())) .and_then(|res| res) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { let mut inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is already shut down".into())); + return Err(MetricError::Other("reader is already shut down".into())); } let (sender, receiver) = oneshot::channel(); inner .message_sender .try_send(Message::Shutdown(sender)) - .map_err(|e| MetricsError::Other(e.to_string()))?; + .map_err(|e| MetricError::Other(e.to_string()))?; drop(inner); // don't hold lock when blocking on future let shutdown_result = futures_executor::block_on(receiver) - .map_err(|err| MetricsError::Other(err.to_string()))?; + .map_err(|err| MetricError::Other(err.to_string()))?; // Acquire the lock again to set the shutdown flag let mut inner = self.inner.lock()?; @@ -393,7 +393,7 @@ mod tests { metrics::data::ResourceMetrics, metrics::reader::MetricReader, metrics::SdkMeterProvider, runtime, testing::metrics::InMemoryMetricsExporter, Resource, }; - use opentelemetry::metrics::{MeterProvider, MetricsError}; + use opentelemetry::metrics::{MeterProvider, MetricError}; use std::sync::mpsc; #[test] @@ -449,7 +449,7 @@ mod tests { // Assert assert!( - matches!(result.unwrap_err(), MetricsError::Other(err) if err == "reader is not registered") + matches!(result.unwrap_err(), MetricError::Other(err) if err == "reader is not registered") ); } diff --git a/opentelemetry-sdk/src/metrics/pipeline.rs b/opentelemetry-sdk/src/metrics/pipeline.rs index e02e35ea2c..1f60b2c1af 100644 --- a/opentelemetry-sdk/src/metrics/pipeline.rs +++ b/opentelemetry-sdk/src/metrics/pipeline.rs @@ -7,7 +7,7 @@ use std::{ use opentelemetry::{ global, - metrics::{MetricsError, Result}, + metrics::{MetricError, MetricResult}, InstrumentationScope, KeyValue, }; @@ -88,19 +88,19 @@ impl Pipeline { } /// Send accumulated telemetry - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { self.reader.force_flush() } /// Shut down pipeline - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { self.reader.shutdown() } } impl SdkProducer for Pipeline { /// Returns aggregated metrics from a single collection. - fn produce(&self, rm: &mut ResourceMetrics) -> Result<()> { + fn produce(&self, rm: &mut ResourceMetrics) -> MetricResult<()> { let inner = self.inner.lock()?; for cb in &inner.callbacks { // TODO consider parallel callbacks. @@ -184,7 +184,7 @@ impl fmt::Debug for InstrumentSync { } } -type Cache = Mutex>>>>>; +type Cache = Mutex>>>>>; /// Facilitates inserting of new instruments from a single scope into a pipeline. struct Inserter { @@ -247,13 +247,13 @@ where &self, inst: Instrument, boundaries: Option<&[f64]>, - ) -> Result>>> { + ) -> MetricResult>>> { let mut matched = false; let mut measures = vec![]; let mut errs = vec![]; let kind = match inst.kind { Some(kind) => kind, - None => return Err(MetricsError::Other("instrument must have a kind".into())), + None => return Err(MetricError::Other("instrument must have a kind".into())), }; // The cache will return the same Aggregator instance. Use stream ids to de duplicate. @@ -286,7 +286,7 @@ where if errs.is_empty() { return Ok(measures); } else { - return Err(MetricsError::Other(format!("{errs:?}"))); + return Err(MetricError::Other(format!("{errs:?}"))); } } @@ -315,12 +315,12 @@ where } Ok(measures) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } Err(err) => { errs.push(err); - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } @@ -343,7 +343,7 @@ where scope: &InstrumentationScope, kind: InstrumentKind, mut stream: Stream, - ) -> Result>>> { + ) -> MetricResult>>> { let mut agg = stream .aggregation .take() @@ -355,7 +355,7 @@ where } if let Err(err) = is_aggregator_compatible(&kind, &agg) { - return Err(MetricsError::Other(format!( + return Err(MetricError::Other(format!( "creating aggregator with instrumentKind: {:?}, aggregation {:?}: {:?}", kind, stream.aggregation, err, ))); @@ -400,7 +400,7 @@ where match cached { Ok(opt) => Ok(opt.clone()), - Err(err) => Err(MetricsError::Other(err.to_string())), + Err(err) => Err(MetricError::Other(err.to_string())), } } @@ -414,7 +414,7 @@ where return; } - global::handle_error(MetricsError::Other(format!( + global::handle_error(MetricError::Other(format!( "duplicate metric stream definitions, names: ({} and {}), descriptions: ({} and {}), kinds: ({:?} and {:?}), units: ({:?} and {:?}), and numbers: ({} and {})", existing.name, id.name, existing.description, id.description, @@ -480,7 +480,7 @@ fn aggregate_fn( b: AggregateBuilder, agg: &aggregation::Aggregation, kind: InstrumentKind, -) -> Result>> { +) -> MetricResult>> { fn box_val( (m, ca): (impl internal::Measure, impl internal::ComputeAggregation), ) -> ( @@ -553,7 +553,10 @@ fn aggregate_fn( /// | Observable UpDownCounter | ✓ | | ✓ | ✓ | ✓ | /// | Gauge | ✓ | ✓ | | ✓ | ✓ | /// | Observable Gauge | ✓ | ✓ | | ✓ | ✓ | -fn is_aggregator_compatible(kind: &InstrumentKind, agg: &aggregation::Aggregation) -> Result<()> { +fn is_aggregator_compatible( + kind: &InstrumentKind, + agg: &aggregation::Aggregation, +) -> MetricResult<()> { match agg { Aggregation::Default => Ok(()), Aggregation::ExplicitBucketHistogram { .. } @@ -570,7 +573,7 @@ fn is_aggregator_compatible(kind: &InstrumentKind, agg: &aggregation::Aggregatio ) { return Ok(()); } - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } Aggregation::Sum => { match kind { @@ -582,7 +585,7 @@ fn is_aggregator_compatible(kind: &InstrumentKind, agg: &aggregation::Aggregatio _ => { // TODO: review need for aggregation check after // https://github.com/open-telemetry/opentelemetry-specification/issues/2710 - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } } } @@ -592,7 +595,7 @@ fn is_aggregator_compatible(kind: &InstrumentKind, agg: &aggregation::Aggregatio _ => { // TODO: review need for aggregation check after // https://github.com/open-telemetry/opentelemetry-specification/issues/2710 - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } } } @@ -636,7 +639,7 @@ impl Pipelines { } /// Force flush all pipelines - pub(crate) fn force_flush(&self) -> Result<()> { + pub(crate) fn force_flush(&self) -> MetricResult<()> { let mut errs = vec![]; for pipeline in &self.0 { if let Err(err) = pipeline.force_flush() { @@ -647,12 +650,12 @@ impl Pipelines { if errs.is_empty() { Ok(()) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } /// Shut down all pipelines - pub(crate) fn shutdown(&self) -> Result<()> { + pub(crate) fn shutdown(&self) -> MetricResult<()> { let mut errs = vec![]; for pipeline in &self.0 { if let Err(err) = pipeline.shutdown() { @@ -663,7 +666,7 @@ impl Pipelines { if errs.is_empty() { Ok(()) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } @@ -697,7 +700,7 @@ where &self, id: Instrument, boundaries: Option>, - ) -> Result>>> { + ) -> MetricResult>>> { let (mut measures, mut errs) = (vec![], vec![]); for inserter in &self.inserters { @@ -714,7 +717,7 @@ where } Ok(measures) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } diff --git a/opentelemetry-sdk/src/metrics/reader.rs b/opentelemetry-sdk/src/metrics/reader.rs index d3530ec01f..86982c732b 100644 --- a/opentelemetry-sdk/src/metrics/reader.rs +++ b/opentelemetry-sdk/src/metrics/reader.rs @@ -1,7 +1,7 @@ //! Interfaces for reading and producing metrics use std::{fmt, sync::Weak}; -use opentelemetry::metrics::Result; +use opentelemetry::metrics::MetricResult; use super::{ data::{ResourceMetrics, Temporality}, @@ -34,13 +34,13 @@ pub trait MetricReader: fmt::Debug + Send + Sync + 'static { /// SDK and stores it in the provided [ResourceMetrics] reference. /// /// An error is returned if this is called after shutdown. - fn collect(&self, rm: &mut ResourceMetrics) -> Result<()>; + fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()>; /// Flushes all metric measurements held in an export pipeline. /// /// There is no guaranteed that all telemetry be flushed or all resources have /// been released on error. - fn force_flush(&self) -> Result<()>; + fn force_flush(&self) -> MetricResult<()>; /// Flushes all metric measurements held in an export pipeline and releases any /// held computational resources. @@ -50,7 +50,7 @@ pub trait MetricReader: fmt::Debug + Send + Sync + 'static { /// /// After `shutdown` is called, calls to `collect` will perform no operation and /// instead will return an error indicating the shutdown state. - fn shutdown(&self) -> Result<()>; + fn shutdown(&self) -> MetricResult<()>; /// The output temporality, a function of instrument kind. /// This SHOULD be obtained from the exporter. @@ -62,5 +62,5 @@ pub trait MetricReader: fmt::Debug + Send + Sync + 'static { /// Produces metrics for a [MetricReader]. pub(crate) trait SdkProducer: fmt::Debug + Send + Sync { /// Returns aggregated metrics from a single collection. - fn produce(&self, rm: &mut ResourceMetrics) -> Result<()>; + fn produce(&self, rm: &mut ResourceMetrics) -> MetricResult<()>; } diff --git a/opentelemetry-sdk/src/metrics/view.rs b/opentelemetry-sdk/src/metrics/view.rs index d9f256bd2b..8bc0801a96 100644 --- a/opentelemetry-sdk/src/metrics/view.rs +++ b/opentelemetry-sdk/src/metrics/view.rs @@ -2,7 +2,7 @@ use super::instrument::{Instrument, Stream}; use glob::Pattern; use opentelemetry::{ global, - metrics::{MetricsError, Result}, + metrics::{MetricError, MetricResult}, }; fn empty_view(_inst: &Instrument) -> Option { @@ -100,9 +100,9 @@ impl View for Box { /// let view = new_view(criteria, mask); /// # drop(view); /// ``` -pub fn new_view(criteria: Instrument, mask: Stream) -> Result> { +pub fn new_view(criteria: Instrument, mask: Stream) -> MetricResult> { if criteria.is_empty() { - global::handle_error(MetricsError::Config(format!( + global::handle_error(MetricError::Config(format!( "no criteria provided, dropping view. mask: {mask:?}" ))); return Ok(Box::new(empty_view)); @@ -112,7 +112,7 @@ pub fn new_view(criteria: Instrument, mask: Stream) -> Result> { let match_fn: Box bool + Send + Sync> = if contains_wildcard { if mask.name != "" { - global::handle_error(MetricsError::Config(format!( + global::handle_error(MetricError::Config(format!( "name replacement for multiple instruments, dropping view, criteria: {criteria:?}, mask: {mask:?}" ))); return Ok(Box::new(empty_view)); @@ -120,7 +120,7 @@ pub fn new_view(criteria: Instrument, mask: Stream) -> Result> { let pattern = criteria.name.clone(); let glob_pattern = - Pattern::new(&pattern).map_err(|e| MetricsError::Config(e.to_string()))?; + Pattern::new(&pattern).map_err(|e| MetricError::Config(e.to_string()))?; Box::new(move |i| { glob_pattern.matches(&i.name) @@ -138,7 +138,7 @@ pub fn new_view(criteria: Instrument, mask: Stream) -> Result> { match ma.validate() { Ok(_) => agg = Some(ma.clone()), Err(err) => { - global::handle_error(MetricsError::Other(format!( + global::handle_error(MetricError::Other(format!( "{}, proceeding as if view did not exist. criteria: {:?}, mask: {:?}", err, err_msg_criteria, mask ))); diff --git a/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs b/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs index 8341deb7d7..a119a2ce98 100644 --- a/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs +++ b/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs @@ -2,8 +2,8 @@ use crate::metrics::data; use crate::metrics::data::{Histogram, Metric, ResourceMetrics, ScopeMetrics, Temporality}; use crate::metrics::exporter::PushMetricsExporter; use async_trait::async_trait; -use opentelemetry::metrics::MetricsError; -use opentelemetry::metrics::Result; +use opentelemetry::metrics::MetricError; +use opentelemetry::metrics::MetricResult; use std::collections::VecDeque; use std::fmt; use std::sync::{Arc, Mutex}; @@ -132,7 +132,7 @@ impl InMemoryMetricsExporter { /// /// # Errors /// - /// Returns a `MetricsError` if the internal lock cannot be acquired. + /// Returns a `MetricError` if the internal lock cannot be acquired. /// /// # Example /// @@ -142,11 +142,11 @@ impl InMemoryMetricsExporter { /// let exporter = InMemoryMetricsExporter::default(); /// let finished_metrics = exporter.get_finished_metrics().unwrap(); /// ``` - pub fn get_finished_metrics(&self) -> Result> { + pub fn get_finished_metrics(&self) -> MetricResult> { self.metrics .lock() .map(|metrics_guard| metrics_guard.iter().map(Self::clone_metrics).collect()) - .map_err(MetricsError::from) + .map_err(MetricError::from) } /// Clears the internal storage of finished metrics. @@ -245,24 +245,24 @@ impl InMemoryMetricsExporter { #[async_trait] impl PushMetricsExporter for InMemoryMetricsExporter { - async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> { + async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> { self.metrics .lock() .map(|mut metrics_guard| { metrics_guard.push_back(InMemoryMetricsExporter::clone_metrics(metrics)) }) - .map_err(MetricsError::from) + .map_err(MetricError::from) } - async fn force_flush(&self) -> Result<()> { + async fn force_flush(&self) -> MetricResult<()> { Ok(()) // In this implementation, flush does nothing } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { self.metrics .lock() .map(|mut metrics_guard| metrics_guard.clear()) - .map_err(MetricsError::from)?; + .map_err(MetricError::from)?; Ok(()) } diff --git a/opentelemetry-sdk/src/testing/metrics/metric_reader.rs b/opentelemetry-sdk/src/testing/metrics/metric_reader.rs index 0b67b155a3..a3c3cf6f49 100644 --- a/opentelemetry-sdk/src/testing/metrics/metric_reader.rs +++ b/opentelemetry-sdk/src/testing/metrics/metric_reader.rs @@ -6,7 +6,7 @@ use crate::metrics::{ reader::MetricReader, InstrumentKind, }; -use opentelemetry::metrics::Result; +use opentelemetry::metrics::MetricResult; #[derive(Debug, Clone)] pub struct TestMetricReader { @@ -36,15 +36,15 @@ impl Default for TestMetricReader { impl MetricReader for TestMetricReader { fn register_pipeline(&self, _pipeline: Weak) {} - fn collect(&self, _rm: &mut ResourceMetrics) -> Result<()> { + fn collect(&self, _rm: &mut ResourceMetrics) -> MetricResult<()> { Ok(()) } - fn force_flush(&self) -> Result<()> { + fn force_flush(&self) -> MetricResult<()> { Ok(()) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { let result = self.force_flush(); { let mut is_shutdown = self.is_shutdown.lock().unwrap(); diff --git a/opentelemetry-stdout/src/metrics/exporter.rs b/opentelemetry-stdout/src/metrics/exporter.rs index 093748a997..35a5658950 100644 --- a/opentelemetry-stdout/src/metrics/exporter.rs +++ b/opentelemetry-stdout/src/metrics/exporter.rs @@ -1,7 +1,7 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::{f64, fmt}; -use opentelemetry::metrics::{MetricsError, Result}; +use opentelemetry::metrics::{MetricError, MetricResult}; use opentelemetry_sdk::metrics::{ data::{self, ScopeMetrics, Temporality}, exporter::PushMetricsExporter, @@ -36,9 +36,9 @@ impl fmt::Debug for MetricsExporter { #[async_trait] impl PushMetricsExporter for MetricsExporter { /// Write Metrics to stdout - async fn export(&self, metrics: &mut data::ResourceMetrics) -> Result<()> { + async fn export(&self, metrics: &mut data::ResourceMetrics) -> MetricResult<()> { if self.is_shutdown.load(atomic::Ordering::SeqCst) { - Err(MetricsError::Other("exporter is shut down".into())) + Err(MetricError::Other("exporter is shut down".into())) } else { println!("Metrics"); println!("Resource"); @@ -54,12 +54,12 @@ impl PushMetricsExporter for MetricsExporter { } } - async fn force_flush(&self) -> Result<()> { + async fn force_flush(&self) -> MetricResult<()> { // exporter holds no state, nothing to flush Ok(()) } - fn shutdown(&self) -> Result<()> { + fn shutdown(&self) -> MetricResult<()> { self.is_shutdown.store(true, atomic::Ordering::SeqCst); Ok(()) } diff --git a/opentelemetry/Cargo.toml b/opentelemetry/Cargo.toml index 75b6597a57..0a4ef72242 100644 --- a/opentelemetry/Cargo.toml +++ b/opentelemetry/Cargo.toml @@ -26,6 +26,7 @@ futures-sink = "0.3" once_cell = { workspace = true } pin-project-lite = { workspace = true, optional = true } thiserror = { workspace = true } +tracing = {workspace = true, optional = true} # optional for opentelemetry internal logging [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dependencies] js-sys = "0.3.63" @@ -38,6 +39,7 @@ testing = ["trace", "metrics"] logs = [] logs_level_enabled = ["logs"] otel_unstable = [] +internal-logs = ["tracing"] [dev-dependencies] opentelemetry_sdk = { path = "../opentelemetry-sdk", features = ["logs_level_enabled"]} # for documentation tests diff --git a/opentelemetry/src/global/error_handler.rs b/opentelemetry/src/global/error_handler.rs index 87149c1b39..3a717154bf 100644 --- a/opentelemetry/src/global/error_handler.rs +++ b/opentelemetry/src/global/error_handler.rs @@ -4,7 +4,7 @@ use std::sync::RwLock; #[cfg(feature = "logs")] use crate::logs::LogError; #[cfg(feature = "metrics")] -use crate::metrics::MetricsError; +use crate::metrics::MetricError; use crate::propagation::PropagationError; #[cfg(feature = "trace")] use crate::trace::TraceError; @@ -25,7 +25,7 @@ pub enum Error { #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))] #[error(transparent)] /// An issue raised by the metrics module. - Metric(#[from] MetricsError), + Metric(#[from] MetricError), #[cfg(feature = "logs")] #[cfg_attr(docsrs, doc(cfg(feature = "logs")))] diff --git a/opentelemetry/src/metrics/mod.rs b/opentelemetry/src/metrics/mod.rs index 417a37ff5e..6c3a4381fb 100644 --- a/opentelemetry/src/metrics/mod.rs +++ b/opentelemetry/src/metrics/mod.rs @@ -22,12 +22,12 @@ pub use instruments::{ pub use meter::{Meter, MeterProvider}; /// A specialized `Result` type for metric operations. -pub type Result = result::Result; +pub type MetricResult = result::Result; /// Errors returned by the metrics API. #[derive(Error, Debug)] #[non_exhaustive] -pub enum MetricsError { +pub enum MetricError { /// Other errors not covered by specific cases. #[error("Metrics error: {0}")] Other(String), @@ -44,15 +44,15 @@ pub enum MetricsError { InvalidInstrumentConfiguration(&'static str), } -impl From for MetricsError { +impl From for MetricError { fn from(err: T) -> Self { - MetricsError::ExportErr(Box::new(err)) + MetricError::ExportErr(Box::new(err)) } } -impl From> for MetricsError { +impl From> for MetricError { fn from(err: PoisonError) -> Self { - MetricsError::Other(err.to_string()) + MetricError::Other(err.to_string()) } } diff --git a/opentelemetry/src/trace/context.rs b/opentelemetry/src/trace/context.rs index 681c7b2e0c..723a525f88 100644 --- a/opentelemetry/src/trace/context.rs +++ b/opentelemetry/src/trace/context.rs @@ -1,6 +1,6 @@ //! Context extensions for tracing use crate::{ - global, + global, otel_debug, trace::{Span, SpanContext, Status}, Context, ContextGuard, KeyValue, }; @@ -55,7 +55,13 @@ impl SpanRef<'_> { if let Some(ref inner) = self.0.inner { match inner.lock() { Ok(mut locked) => f(&mut locked), - Err(err) => global::handle_error(err), + Err(err) => { + otel_debug!( + name: "SpanRef.LockFailed", + message = "Failed to acquire lock for SpanRef: {:?}", + reason = format!("{:?}", err), + span_context = format!("{:?}", self.0.span_context)); + } } } }