diff --git a/opentelemetry-appender-log/src/lib.rs b/opentelemetry-appender-log/src/lib.rs
index f20b5f65ff..0fe09acde3 100644
--- a/opentelemetry-appender-log/src/lib.rs
+++ b/opentelemetry-appender-log/src/lib.rs
@@ -97,11 +97,10 @@
use log::{Level, Metadata, Record};
use opentelemetry::{
logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity},
- Key,
+ InstrumentationScope, Key,
};
#[cfg(feature = "experimental_metadata_attributes")]
use opentelemetry_semantic_conventions::attribute::{CODE_FILEPATH, CODE_LINENO, CODE_NAMESPACE};
-use std::borrow::Cow;
pub struct OpenTelemetryLogBridge
where
@@ -170,11 +169,12 @@ where
L: Logger + Send + Sync,
{
pub fn new(provider: &P) -> Self {
+ let scope = InstrumentationScope::builder("opentelemetry-log-appender")
+ .with_version(env!("CARGO_PKG_VERSION"))
+ .build();
+
OpenTelemetryLogBridge {
- logger: provider
- .logger_builder("opentelemetry-log-appender")
- .with_version(Cow::Borrowed(env!("CARGO_PKG_VERSION")))
- .build(),
+ logger: provider.logger_with_scope(scope),
_phantom: Default::default(),
}
}
diff --git a/opentelemetry-appender-tracing/benches/logs.rs b/opentelemetry-appender-tracing/benches/logs.rs
index a5ebb83249..0237e4a769 100644
--- a/opentelemetry-appender-tracing/benches/logs.rs
+++ b/opentelemetry-appender-tracing/benches/logs.rs
@@ -16,7 +16,7 @@
use async_trait::async_trait;
use criterion::{criterion_group, criterion_main, Criterion};
use opentelemetry::logs::LogResult;
-use opentelemetry::{InstrumentationLibrary, KeyValue};
+use opentelemetry::{InstrumentationScope, KeyValue};
use opentelemetry_appender_tracing::layer as tracing_layer;
use opentelemetry_sdk::export::logs::{LogBatch, LogExporter};
use opentelemetry_sdk::logs::{LogProcessor, LogRecord, LoggerProvider};
@@ -55,7 +55,7 @@ impl NoopProcessor {
}
impl LogProcessor for NoopProcessor {
- fn emit(&self, _: &mut LogRecord, _: &InstrumentationLibrary) {
+ fn emit(&self, _: &mut LogRecord, _: &InstrumentationScope) {
// no-op
}
diff --git a/opentelemetry-appender-tracing/src/layer.rs b/opentelemetry-appender-tracing/src/layer.rs
index fbbf8e4d97..0408eec64c 100644
--- a/opentelemetry-appender-tracing/src/layer.rs
+++ b/opentelemetry-appender-tracing/src/layer.rs
@@ -1,6 +1,6 @@
use opentelemetry::{
logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity},
- Key,
+ InstrumentationScope, Key,
};
use std::borrow::Cow;
use tracing_core::Level;
@@ -136,11 +136,12 @@ where
L: Logger + Send + Sync,
{
pub fn new(provider: &P) -> Self {
+ let scope = InstrumentationScope::builder(INSTRUMENTATION_LIBRARY_NAME)
+ .with_version(Cow::Borrowed(env!("CARGO_PKG_VERSION")))
+ .build();
+
OpenTelemetryTracingBridge {
- logger: provider
- .logger_builder(INSTRUMENTATION_LIBRARY_NAME)
- .with_version(Cow::Borrowed(env!("CARGO_PKG_VERSION")))
- .build(),
+ logger: provider.logger_with_scope(scope),
_phantom: Default::default(),
}
}
diff --git a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs
index 387cf6e7c9..029efaaa30 100644
--- a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs
+++ b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs
@@ -2,8 +2,8 @@ use once_cell::sync::Lazy;
use opentelemetry::{
global,
metrics::MetricsError,
- trace::{TraceContextExt, TraceError, Tracer, TracerProvider as _},
- KeyValue,
+ trace::{TraceContextExt, TraceError, Tracer},
+ InstrumentationScope, KeyValue,
};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::WithExportConfig;
@@ -128,16 +128,13 @@ async fn main() -> Result<(), Box> {
.init();
let common_scope_attributes = vec![KeyValue::new("scope-key", "scope-value")];
- let tracer = global::tracer_provider()
- .tracer_builder("basic")
- .with_attributes(common_scope_attributes.clone())
+ let scope = InstrumentationScope::builder("basic")
+ .with_version("1.0")
+ .with_attributes(common_scope_attributes)
.build();
- let meter = global::meter_with_version(
- "basic",
- Some("v1.0"),
- Some("schema_url"),
- Some(common_scope_attributes.clone()),
- );
+
+ let tracer = global::tracer_with_scope(scope.clone());
+ let meter = global::meter_with_scope(scope);
let counter = meter
.u64_counter("test_counter")
diff --git a/opentelemetry-otlp/examples/basic-otlp/src/main.rs b/opentelemetry-otlp/examples/basic-otlp/src/main.rs
index 8da8dff7f2..60f2922a35 100644
--- a/opentelemetry-otlp/examples/basic-otlp/src/main.rs
+++ b/opentelemetry-otlp/examples/basic-otlp/src/main.rs
@@ -1,12 +1,9 @@
use once_cell::sync::Lazy;
-use opentelemetry::global;
use opentelemetry::logs::LogError;
use opentelemetry::metrics::MetricsError;
-use opentelemetry::trace::{TraceError, TracerProvider};
-use opentelemetry::{
- trace::{TraceContextExt, Tracer},
- KeyValue,
-};
+use opentelemetry::trace::{TraceContextExt, TraceError, Tracer};
+use opentelemetry::KeyValue;
+use opentelemetry::{global, InstrumentationScope};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{LogExporter, MetricsExporter, SpanExporter, WithExportConfig};
use opentelemetry_sdk::logs::LoggerProvider;
@@ -108,16 +105,13 @@ async fn main() -> Result<(), Box> {
.init();
let common_scope_attributes = vec![KeyValue::new("scope-key", "scope-value")];
- let tracer = global::tracer_provider()
- .tracer_builder("basic")
- .with_attributes(common_scope_attributes.clone())
+ let scope = InstrumentationScope::builder("basic")
+ .with_version("1.0")
+ .with_attributes(common_scope_attributes)
.build();
- let meter = global::meter_with_version(
- "basic",
- Some("v1.0"),
- Some("schema_url"),
- Some(common_scope_attributes.clone()),
- );
+
+ let tracer = global::tracer_with_scope(scope.clone());
+ let meter = global::meter_with_scope(scope);
let counter = meter
.u64_counter("test_counter")
diff --git a/opentelemetry-otlp/tests/integration_test/expected/serialized_traces.json b/opentelemetry-otlp/tests/integration_test/expected/serialized_traces.json
index e5982877cf..f1d64108ad 100644
--- a/opentelemetry-otlp/tests/integration_test/expected/serialized_traces.json
+++ b/opentelemetry-otlp/tests/integration_test/expected/serialized_traces.json
@@ -26,7 +26,7 @@
"spanId": "cd7cf7bf939930b7",
"traceState": "",
"parentSpanId": "d58cf2d702a061e0",
- "flags": 0,
+ "flags": 1,
"name": "Sub operation...",
"kind": 1,
"startTimeUnixNano": "1703985537070566698",
@@ -55,40 +55,13 @@
"message": "",
"code": 0
}
- }
- ],
- "schemaUrl": ""
- }
- ],
- "schemaUrl": ""
- },
- {
- "resource": {
- "attributes": [
- {
- "key": "service.name",
- "value": {
- "stringValue": "basic-otlp-tracing-example"
- }
- }
- ],
- "droppedAttributesCount": 0
- },
- "scopeSpans": [
- {
- "scope": {
- "name": "ex.com/basic",
- "version": "",
- "attributes": [],
- "droppedAttributesCount": 0
- },
- "spans": [
+ },
{
"traceId": "9b458af7378cba65253d7042d34fc72e",
"spanId": "d58cf2d702a061e0",
"traceState": "",
"parentSpanId": "",
- "flags": 0,
+ "flags": 1,
"name": "operation",
"kind": 1,
"startTimeUnixNano": "1703985537070558635",
@@ -112,12 +85,6 @@
"value": {
"intValue": "100"
}
- },
- {
- "key": "number/int",
- "value": {
- "intValue": "100"
- }
}
],
"droppedAttributesCount": 0
diff --git a/opentelemetry-proto/src/transform/common.rs b/opentelemetry-proto/src/transform/common.rs
index c37a3dbec1..0821165c89 100644
--- a/opentelemetry-proto/src/transform/common.rs
+++ b/opentelemetry-proto/src/transform/common.rs
@@ -44,13 +44,13 @@ pub mod tonic {
impl
From<(
- opentelemetry_sdk::InstrumentationLibrary,
+ opentelemetry::InstrumentationScope,
Option>,
)> for InstrumentationScope
{
fn from(
data: (
- opentelemetry_sdk::InstrumentationLibrary,
+ opentelemetry::InstrumentationScope,
Option>,
),
) -> Self {
@@ -75,13 +75,13 @@ pub mod tonic {
impl
From<(
- &opentelemetry_sdk::InstrumentationLibrary,
+ &opentelemetry::InstrumentationScope,
Option>,
)> for InstrumentationScope
{
fn from(
data: (
- &opentelemetry_sdk::InstrumentationLibrary,
+ &opentelemetry::InstrumentationScope,
Option>,
),
) -> Self {
diff --git a/opentelemetry-proto/src/transform/logs.rs b/opentelemetry-proto/src/transform/logs.rs
index 48e100c60d..52fd3cace4 100644
--- a/opentelemetry-proto/src/transform/logs.rs
+++ b/opentelemetry-proto/src/transform/logs.rs
@@ -143,7 +143,7 @@ pub mod tonic {
From<(
(
&opentelemetry_sdk::logs::LogRecord,
- &opentelemetry::InstrumentationLibrary,
+ &opentelemetry::InstrumentationScope,
),
&ResourceAttributesWithSchema,
)> for ResourceLogs
@@ -152,7 +152,7 @@ pub mod tonic {
data: (
(
&opentelemetry_sdk::logs::LogRecord,
- &opentelemetry::InstrumentationLibrary,
+ &opentelemetry::InstrumentationScope,
),
&ResourceAttributesWithSchema,
),
@@ -189,7 +189,7 @@ pub mod tonic {
Cow<'static, str>,
Vec<(
&opentelemetry_sdk::logs::LogRecord,
- &opentelemetry::InstrumentationLibrary,
+ &opentelemetry::InstrumentationScope,
)>,
>,
(log_record, instrumentation)| {
@@ -235,19 +235,19 @@ pub mod tonic {
mod tests {
use crate::transform::common::tonic::ResourceAttributesWithSchema;
use opentelemetry::logs::LogRecord as _;
- use opentelemetry::InstrumentationLibrary;
+ use opentelemetry::InstrumentationScope;
use opentelemetry_sdk::{export::logs::LogBatch, logs::LogRecord, Resource};
use std::time::SystemTime;
fn create_test_log_data(
instrumentation_name: &str,
_message: &str,
- ) -> (LogRecord, InstrumentationLibrary) {
+ ) -> (LogRecord, InstrumentationScope) {
let mut logrecord = LogRecord::default();
logrecord.set_timestamp(SystemTime::now());
logrecord.set_observed_timestamp(SystemTime::now());
let instrumentation =
- InstrumentationLibrary::builder(instrumentation_name.to_string()).build();
+ InstrumentationScope::builder(instrumentation_name.to_string()).build();
(logrecord, instrumentation)
}
diff --git a/opentelemetry-proto/src/transform/trace.rs b/opentelemetry-proto/src/transform/trace.rs
index 12871b33aa..27018d624a 100644
--- a/opentelemetry-proto/src/transform/trace.rs
+++ b/opentelemetry-proto/src/transform/trace.rs
@@ -101,12 +101,12 @@ pub mod tonic {
schema_url: resource.schema_url.clone().unwrap_or_default(),
scope_spans: vec![ScopeSpans {
schema_url: source_span
- .instrumentation_lib
+ .instrumentation_scope
.schema_url
.as_ref()
.map(ToString::to_string)
.unwrap_or_default(),
- scope: Some((source_span.instrumentation_lib, None).into()),
+ scope: Some((source_span.instrumentation_scope, None).into()),
spans: vec![Span {
trace_id: source_span.span_context.trace_id().to_bytes().to_vec(),
span_id: source_span.span_context.span_id().to_bytes().to_vec(),
@@ -155,12 +155,11 @@ pub mod tonic {
spans: Vec,
resource: &ResourceAttributesWithSchema,
) -> Vec {
- // Group spans by their instrumentation library
+ // Group spans by their instrumentation scope
let scope_map = spans.iter().fold(
HashMap::new(),
- |mut scope_map: HashMap<&opentelemetry_sdk::InstrumentationLibrary, Vec<&SpanData>>,
- span| {
- let instrumentation = &span.instrumentation_lib;
+ |mut scope_map: HashMap<&opentelemetry::InstrumentationScope, Vec<&SpanData>>, span| {
+ let instrumentation = &span.instrumentation_scope;
scope_map.entry(instrumentation).or_default().push(span);
scope_map
},
@@ -198,11 +197,11 @@ mod tests {
use opentelemetry::trace::{
SpanContext, SpanId, SpanKind, Status, TraceFlags, TraceId, TraceState,
};
+ use opentelemetry::InstrumentationScope;
use opentelemetry::KeyValue;
use opentelemetry_sdk::export::trace::SpanData;
use opentelemetry_sdk::resource::Resource;
use opentelemetry_sdk::trace::{SpanEvents, SpanLinks};
- use opentelemetry_sdk::InstrumentationLibrary;
use std::borrow::Cow;
use std::time::{Duration, SystemTime};
@@ -227,7 +226,7 @@ mod tests {
events: SpanEvents::default(),
links: SpanLinks::default(),
status: Status::Unset,
- instrumentation_lib: InstrumentationLibrary::builder(instrumentation_name).build(),
+ instrumentation_scope: InstrumentationScope::builder(instrumentation_name).build(),
}
}
diff --git a/opentelemetry-sdk/CHANGELOG.md b/opentelemetry-sdk/CHANGELOG.md
index 515cd5633b..0841dc708c 100644
--- a/opentelemetry-sdk/CHANGELOG.md
+++ b/opentelemetry-sdk/CHANGELOG.md
@@ -19,6 +19,12 @@ Now:
```rust
let counter = meter.u64_counter("my_counter").build();
```
+- **BREAKING**: [#2220](https://github.com/open-telemetry/opentelemetry-rust/pull/2220)
+ - Removed `InstrumentationLibrary` re-export and its `Scope` alias, use `opentelemetry::InstrumentationLibrary` instead.
+ - Unified builders across signals
+ - Removed deprecated `LoggerProvider::versioned_logger`, `TracerProvider::versioned_tracer`
+ - Removed `MeterProvider::versioned_meter`
+ - Replaced these methods with `LoggerProvider::logger_with_scope`, `TracerProvider::logger_with_scope`, `MeterProvider::meter_with_scope`
## v0.26.0
Released 2024-Sep-30
diff --git a/opentelemetry-sdk/benches/batch_span_processor.rs b/opentelemetry-sdk/benches/batch_span_processor.rs
index abc7d0df02..ed20c45a06 100644
--- a/opentelemetry-sdk/benches/batch_span_processor.rs
+++ b/opentelemetry-sdk/benches/batch_span_processor.rs
@@ -32,7 +32,7 @@ fn get_span_data() -> Vec {
events: SpanEvents::default(),
links: SpanLinks::default(),
status: Status::Unset,
- instrumentation_lib: Default::default(),
+ instrumentation_scope: Default::default(),
})
.collect::>()
}
diff --git a/opentelemetry-sdk/benches/log.rs b/opentelemetry-sdk/benches/log.rs
index 20d3503100..ca8a76a414 100644
--- a/opentelemetry-sdk/benches/log.rs
+++ b/opentelemetry-sdk/benches/log.rs
@@ -25,7 +25,7 @@ use opentelemetry::logs::{
};
use opentelemetry::trace::Tracer;
use opentelemetry::trace::TracerProvider as _;
-use opentelemetry::{InstrumentationLibrary, Key};
+use opentelemetry::{InstrumentationScope, Key};
use opentelemetry_sdk::logs::{LogProcessor, LogRecord, Logger, LoggerProvider};
use opentelemetry_sdk::trace;
use opentelemetry_sdk::trace::{Sampler, TracerProvider};
@@ -34,7 +34,7 @@ use opentelemetry_sdk::trace::{Sampler, TracerProvider};
struct NoopProcessor;
impl LogProcessor for NoopProcessor {
- fn emit(&self, _data: &mut LogRecord, _library: &InstrumentationLibrary) {}
+ fn emit(&self, _data: &mut LogRecord, _scope: &InstrumentationScope) {}
fn force_flush(&self) -> LogResult<()> {
Ok(())
diff --git a/opentelemetry-sdk/benches/log_exporter.rs b/opentelemetry-sdk/benches/log_exporter.rs
index 3549c08af5..c3c027f3e1 100644
--- a/opentelemetry-sdk/benches/log_exporter.rs
+++ b/opentelemetry-sdk/benches/log_exporter.rs
@@ -18,7 +18,7 @@ use criterion::{criterion_group, criterion_main, Criterion};
use opentelemetry::logs::{LogRecord as _, LogResult, Logger as _, LoggerProvider as _, Severity};
-use opentelemetry::InstrumentationLibrary;
+use opentelemetry::InstrumentationScope;
use opentelemetry_sdk::export::logs::LogBatch;
use opentelemetry_sdk::logs::LogProcessor;
use opentelemetry_sdk::logs::LogRecord;
@@ -65,9 +65,9 @@ impl ExportingProcessorWithFuture {
}
impl LogProcessor for ExportingProcessorWithFuture {
- fn emit(&self, record: &mut LogRecord, library: &InstrumentationLibrary) {
+ fn emit(&self, record: &mut LogRecord, scope: &InstrumentationScope) {
let mut exporter = self.exporter.lock().expect("lock error");
- let logs = [(record as &LogRecord, library)];
+ let logs = [(record as &LogRecord, scope)];
futures_executor::block_on(exporter.export(LogBatch::new(&logs)));
}
@@ -94,8 +94,8 @@ impl ExportingProcessorWithoutFuture {
}
impl LogProcessor for ExportingProcessorWithoutFuture {
- fn emit(&self, record: &mut LogRecord, library: &InstrumentationLibrary) {
- let logs = [(record as &LogRecord, library)];
+ fn emit(&self, record: &mut LogRecord, scope: &InstrumentationScope) {
+ let logs = [(record as &LogRecord, scope)];
self.exporter
.lock()
.expect("lock error")
diff --git a/opentelemetry-sdk/benches/log_processor.rs b/opentelemetry-sdk/benches/log_processor.rs
index 1bc0a130b4..03cd71549c 100644
--- a/opentelemetry-sdk/benches/log_processor.rs
+++ b/opentelemetry-sdk/benches/log_processor.rs
@@ -18,8 +18,10 @@ use std::{
};
use criterion::{criterion_group, criterion_main, Criterion};
-use opentelemetry::logs::{LogRecord as _, LogResult, Logger as _, LoggerProvider as _, Severity};
-use opentelemetry::InstrumentationLibrary;
+use opentelemetry::{
+ logs::{LogRecord as _, LogResult, Logger as _, LoggerProvider as _, Severity},
+ InstrumentationScope,
+};
use opentelemetry_sdk::logs::{LogProcessor, LogRecord, Logger, LoggerProvider};
// Run this benchmark with:
@@ -43,7 +45,7 @@ fn create_log_record(logger: &Logger) -> LogRecord {
struct NoopProcessor;
impl LogProcessor for NoopProcessor {
- fn emit(&self, _data: &mut LogRecord, _library: &InstrumentationLibrary) {}
+ fn emit(&self, _data: &mut LogRecord, _scope: &InstrumentationScope) {}
fn force_flush(&self) -> LogResult<()> {
Ok(())
@@ -58,7 +60,7 @@ impl LogProcessor for NoopProcessor {
struct CloningProcessor;
impl LogProcessor for CloningProcessor {
- fn emit(&self, data: &mut LogRecord, _library: &InstrumentationLibrary) {
+ fn emit(&self, data: &mut LogRecord, _scope: &InstrumentationScope) {
let _data_cloned = data.clone();
}
@@ -73,8 +75,8 @@ impl LogProcessor for CloningProcessor {
#[derive(Debug)]
struct SendToChannelProcessor {
- sender: std::sync::mpsc::Sender<(LogRecord, InstrumentationLibrary)>,
- receiver: Arc>>,
+ sender: std::sync::mpsc::Sender<(LogRecord, InstrumentationScope)>,
+ receiver: Arc>>,
}
impl SendToChannelProcessor {
@@ -101,8 +103,8 @@ impl SendToChannelProcessor {
}
impl LogProcessor for SendToChannelProcessor {
- fn emit(&self, record: &mut LogRecord, library: &InstrumentationLibrary) {
- let res = self.sender.send((record.clone(), library.clone()));
+ fn emit(&self, record: &mut LogRecord, scope: &InstrumentationScope) {
+ let res = self.sender.send((record.clone(), scope.clone()));
if res.is_err() {
println!("Error sending log data to channel {0}", res.err().unwrap());
}
diff --git a/opentelemetry-sdk/src/export/logs/mod.rs b/opentelemetry-sdk/src/export/logs/mod.rs
index 8056f28222..2656544ce0 100644
--- a/opentelemetry-sdk/src/export/logs/mod.rs
+++ b/opentelemetry-sdk/src/export/logs/mod.rs
@@ -4,26 +4,24 @@ use crate::Resource;
use async_trait::async_trait;
#[cfg(feature = "logs_level_enabled")]
use opentelemetry::logs::Severity;
-use opentelemetry::{
- logs::{LogError, LogResult},
- InstrumentationLibrary,
-};
+use opentelemetry::logs::{LogError, LogResult};
+use opentelemetry::InstrumentationScope;
use std::fmt::Debug;
/// A batch of log records to be exported by a `LogExporter`.
///
/// The `LogBatch` struct holds a collection of log records along with their associated
-/// instrumentation libraries. This structure is used to group log records together for efficient
+/// instrumentation scopes. This structure is used to group log records together for efficient
/// export operations.
///
/// # Type Parameters
-/// - `'a`: The lifetime of the references to the log records and instrumentation libraries.
+/// - `'a`: The lifetime of the references to the log records and instrumentation scopes.
///
#[derive(Debug)]
pub struct LogBatch<'a> {
/// The data field contains a slice of tuples, where each tuple consists of a reference to
- /// a `LogRecord` and a reference to an `InstrumentationLibrary`.
- data: &'a [(&'a LogRecord, &'a InstrumentationLibrary)],
+ /// a `LogRecord` and a reference to an `InstrumentationScope`.
+ data: &'a [(&'a LogRecord, &'a InstrumentationScope)],
}
impl<'a> LogBatch<'a> {
@@ -32,32 +30,32 @@ impl<'a> LogBatch<'a> {
/// # Arguments
///
/// * `data` - A slice of tuples, where each tuple consists of a reference to a `LogRecord`
- /// and a reference to an `InstrumentationLibrary`. These tuples represent the log records
- /// and their associated instrumentation libraries to be exported.
+ /// and a reference to an `InstrumentationScope`. These tuples represent the log records
+ /// and their associated instrumentation scopes to be exported.
///
/// # Returns
///
- /// A `LogBatch` instance containing the provided log records and instrumentation libraries.
+ /// A `LogBatch` instance containing the provided log records and instrumentation scopes.
///
/// Note - this is not a public function, and should not be used directly. This would be
/// made private in the future.
- pub fn new(data: &'a [(&'a LogRecord, &'a InstrumentationLibrary)]) -> LogBatch<'a> {
+ pub fn new(data: &'a [(&'a LogRecord, &'a InstrumentationScope)]) -> LogBatch<'a> {
LogBatch { data }
}
}
impl LogBatch<'_> {
- /// Returns an iterator over the log records and instrumentation libraries in the batch.
+ /// Returns an iterator over the log records and instrumentation scopes in the batch.
///
/// Each item yielded by the iterator is a tuple containing references to a `LogRecord`
- /// and an `InstrumentationLibrary`.
+ /// and an `InstrumentationScope`.
///
/// # Returns
///
- /// An iterator that yields references to the `LogRecord` and `InstrumentationLibrary` in the batch.
+ /// An iterator that yields references to the `LogRecord` and `InstrumentationScope` in the batch.
///
- pub fn iter(&self) -> impl Iterator- {
+ pub fn iter(&self) -> impl Iterator
- {
self.data
.iter()
.map(|(record, library)| (*record, *library))
@@ -67,16 +65,16 @@ impl LogBatch<'_> {
/// `LogExporter` defines the interface that log exporters should implement.
#[async_trait]
pub trait LogExporter: Send + Sync + Debug {
- /// Exports a batch of log records and their associated instrumentation libraries.
+ /// Exports a batch of log records and their associated instrumentation scopes.
///
/// The `export` method is responsible for sending a batch of log records to an external
/// destination. It takes a `LogBatch` as an argument, which contains references to the
- /// log records and their corresponding instrumentation libraries. The method returns
+ /// log records and their corresponding instrumentation scopes. The method returns
/// a `LogResult` indicating the success or failure of the export operation.
///
/// # Arguments
///
- /// * `batch` - A `LogBatch` containing the log records and instrumentation libraries
+ /// * `batch` - A `LogBatch` containing the log records and instrumentation scopes
/// to be exported.
///
/// # Returns
diff --git a/opentelemetry-sdk/src/export/trace.rs b/opentelemetry-sdk/src/export/trace.rs
index 4b43e00c36..c606d85b1a 100644
--- a/opentelemetry-sdk/src/export/trace.rs
+++ b/opentelemetry-sdk/src/export/trace.rs
@@ -2,7 +2,7 @@
use crate::Resource;
use futures_util::future::BoxFuture;
use opentelemetry::trace::{SpanContext, SpanId, SpanKind, Status, TraceError};
-use opentelemetry::KeyValue;
+use opentelemetry::{InstrumentationScope, KeyValue};
use std::borrow::Cow;
use std::fmt::Debug;
use std::time::SystemTime;
@@ -95,6 +95,6 @@ pub struct SpanData {
pub links: crate::trace::SpanLinks,
/// Span status
pub status: Status,
- /// Instrumentation library that produced this span
- pub instrumentation_lib: crate::InstrumentationLibrary,
+ /// Instrumentation scope that produced this span
+ pub instrumentation_scope: InstrumentationScope,
}
diff --git a/opentelemetry-sdk/src/instrumentation.rs b/opentelemetry-sdk/src/instrumentation.rs
deleted file mode 100644
index 75a74efa73..0000000000
--- a/opentelemetry-sdk/src/instrumentation.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-pub use opentelemetry::InstrumentationLibrary;
-
-/// A logical unit of the application code with which the emitted telemetry can
-/// be associated.
-pub type Scope = InstrumentationLibrary;
diff --git a/opentelemetry-sdk/src/lib.rs b/opentelemetry-sdk/src/lib.rs
index 00df78fe3c..273cb183c8 100644
--- a/opentelemetry-sdk/src/lib.rs
+++ b/opentelemetry-sdk/src/lib.rs
@@ -122,7 +122,7 @@
pub mod export;
pub(crate) mod growable_array;
-mod instrumentation;
+
#[cfg(feature = "logs")]
#[cfg_attr(docsrs, doc(cfg(feature = "logs")))]
pub mod logs;
@@ -146,6 +146,5 @@ pub mod trace;
#[doc(hidden)]
pub mod util;
-pub use instrumentation::{InstrumentationLibrary, Scope};
#[doc(inline)]
pub use resource::Resource;
diff --git a/opentelemetry-sdk/src/logs/log_emitter.rs b/opentelemetry-sdk/src/logs/log_emitter.rs
index 71b02dc158..1271f0ddd0 100644
--- a/opentelemetry-sdk/src/logs/log_emitter.rs
+++ b/opentelemetry-sdk/src/logs/log_emitter.rs
@@ -4,17 +4,20 @@ use opentelemetry::{
logs::{LogError, LogResult},
otel_debug,
trace::TraceContextExt,
- Context, InstrumentationLibrary,
+ Context, InstrumentationScope,
};
#[cfg(feature = "logs_level_enabled")]
use opentelemetry::logs::Severity;
+use std::time::SystemTime;
use std::{
borrow::Cow,
- sync::{atomic::Ordering, Arc},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
};
-use std::{sync::atomic::AtomicBool, time::SystemTime};
use once_cell::sync::Lazy;
@@ -51,42 +54,23 @@ const DEFAULT_COMPONENT_NAME: &str = "rust.opentelemetry.io/sdk/logger";
impl opentelemetry::logs::LoggerProvider for LoggerProvider {
type Logger = Logger;
- /// Create a new versioned `Logger` instance.
- fn versioned_logger(
- &self,
- name: impl Into>,
- version: Option>,
- schema_url: Option>,
- attributes: Option>,
- ) -> Logger {
- let name = name.into();
- let component_name = if name.is_empty() {
- Cow::Borrowed(DEFAULT_COMPONENT_NAME)
- } else {
- name
- };
-
- let mut builder = self.logger_builder(component_name);
+ fn logger(&self, name: impl Into>) -> Self::Logger {
+ let mut name = name.into();
- if let Some(v) = version {
- builder = builder.with_version(v);
- }
- if let Some(s) = schema_url {
- builder = builder.with_schema_url(s);
- }
- if let Some(a) = attributes {
- builder = builder.with_attributes(a);
- }
+ if name.is_empty() {
+ name = Cow::Borrowed(DEFAULT_COMPONENT_NAME)
+ };
- builder.build()
+ let scope = InstrumentationScope::builder(name).build();
+ self.logger_with_scope(scope)
}
- fn library_logger(&self, library: Arc) -> Self::Logger {
+ fn logger_with_scope(&self, scope: InstrumentationScope) -> Self::Logger {
// If the provider is shutdown, new logger will refer a no-op logger provider.
if self.inner.is_shutdown.load(Ordering::Relaxed) {
- return Logger::new(library, NOOP_LOGGER_PROVIDER.clone());
+ return Logger::new(scope, NOOP_LOGGER_PROVIDER.clone());
}
- Logger::new(library, self.clone())
+ Logger::new(scope, self.clone())
}
}
@@ -250,19 +234,13 @@ impl Builder {
///
/// [`LogRecord`]: opentelemetry::logs::LogRecord
pub struct Logger {
- instrumentation_lib: Arc,
+ scope: InstrumentationScope,
provider: LoggerProvider,
}
impl Logger {
- pub(crate) fn new(
- instrumentation_lib: Arc,
- provider: LoggerProvider,
- ) -> Self {
- Logger {
- instrumentation_lib,
- provider,
- }
+ pub(crate) fn new(scope: InstrumentationScope, provider: LoggerProvider) -> Self {
+ Logger { scope, provider }
}
/// LoggerProvider associated with this logger.
@@ -270,9 +248,9 @@ impl Logger {
&self.provider
}
- /// Instrumentation library information of this logger.
- pub fn instrumentation_library(&self) -> &InstrumentationLibrary {
- &self.instrumentation_lib
+ /// Instrumentation scope of this logger.
+ pub fn instrumentation_scope(&self) -> &InstrumentationScope {
+ &self.scope
}
}
@@ -304,7 +282,7 @@ impl opentelemetry::logs::Logger for Logger {
}
for p in processors {
- p.emit(&mut record, self.instrumentation_library());
+ p.emit(&mut record, self.instrumentation_scope());
}
}
@@ -318,7 +296,7 @@ impl opentelemetry::logs::Logger for Logger {
|| processor.event_enabled(
level,
target,
- self.instrumentation_library().name.as_ref(),
+ self.instrumentation_scope().name.as_ref(),
);
}
enabled
@@ -366,7 +344,7 @@ mod tests {
}
impl LogProcessor for ShutdownTestLogProcessor {
- fn emit(&self, _data: &mut LogRecord, _library: &InstrumentationLibrary) {
+ fn emit(&self, _data: &mut LogRecord, _scope: &InstrumentationScope) {
self.is_shutdown
.lock()
.map(|is_shutdown| {
@@ -745,7 +723,7 @@ mod tests {
}
impl LogProcessor for LazyLogProcessor {
- fn emit(&self, _data: &mut LogRecord, _library: &InstrumentationLibrary) {
+ fn emit(&self, _data: &mut LogRecord, _scope: &InstrumentationScope) {
// nothing to do.
}
@@ -776,7 +754,7 @@ mod tests {
}
impl LogProcessor for CountingShutdownProcessor {
- fn emit(&self, _data: &mut LogRecord, _library: &InstrumentationLibrary) {
+ fn emit(&self, _data: &mut LogRecord, _scope: &InstrumentationScope) {
// nothing to do
}
diff --git a/opentelemetry-sdk/src/logs/log_processor.rs b/opentelemetry-sdk/src/logs/log_processor.rs
index 47489881b0..b70ace08b3 100644
--- a/opentelemetry-sdk/src/logs/log_processor.rs
+++ b/opentelemetry-sdk/src/logs/log_processor.rs
@@ -13,7 +13,7 @@ use futures_util::{
use opentelemetry::logs::Severity;
use opentelemetry::{
logs::{LogError, LogResult},
- otel_debug, otel_error, otel_warn, InstrumentationLibrary,
+ otel_debug, otel_error, otel_warn, InstrumentationScope,
};
use std::sync::atomic::AtomicBool;
@@ -56,8 +56,8 @@ pub trait LogProcessor: Send + Sync + Debug {
///
/// # Parameters
/// - `record`: A mutable reference to `LogData` representing the log record.
- /// - `instrumentation`: The instrumentation library associated with the log record.
- fn emit(&self, data: &mut LogRecord, instrumentation: &InstrumentationLibrary);
+ /// - `instrumentation`: The instrumentation scope associated with the log record.
+ fn emit(&self, data: &mut LogRecord, instrumentation: &InstrumentationScope);
/// Force the logs lying in the cache to be exported.
fn force_flush(&self) -> LogResult<()>;
/// Shuts down the processor.
@@ -95,7 +95,7 @@ impl SimpleLogProcessor {
}
impl LogProcessor for SimpleLogProcessor {
- fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationLibrary) {
+ fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationScope) {
// noop after shutdown
if self.is_shutdown.load(std::sync::atomic::Ordering::Relaxed) {
// this is a warning, as the user is trying to log after the processor has been shutdown
@@ -168,7 +168,7 @@ impl Debug for BatchLogProcessor {
}
impl LogProcessor for BatchLogProcessor {
- fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationLibrary) {
+ fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationScope) {
let result = self.message_sender.try_send(BatchMessage::ExportLog((
record.clone(),
instrumentation.clone(),
@@ -320,7 +320,7 @@ async fn export_with_timeout(
time_out: Duration,
exporter: &mut E,
runtime: &R,
- batch: Vec<(LogRecord, InstrumentationLibrary)>,
+ batch: Vec<(LogRecord, InstrumentationScope)>,
) -> ExportResult
where
R: RuntimeChannel,
@@ -331,7 +331,7 @@ where
}
// TBD - Can we avoid this conversion as it involves heap allocation with new vector?
- let log_vec: Vec<(&LogRecord, &InstrumentationLibrary)> = batch
+ let log_vec: Vec<(&LogRecord, &InstrumentationScope)> = batch
.iter()
.map(|log_data| (&log_data.0, &log_data.1))
.collect();
@@ -515,7 +515,7 @@ where
#[derive(Debug)]
enum BatchMessage {
/// Export logs, usually called when the log is emitted.
- ExportLog((LogRecord, InstrumentationLibrary)),
+ ExportLog((LogRecord, InstrumentationScope)),
/// Flush the current buffer to the backend, it can be triggered by
/// pre configured interval or a call to `force_push` function.
Flush(Option>),
@@ -550,9 +550,8 @@ mod tests {
use opentelemetry::logs::AnyValue;
use opentelemetry::logs::LogRecord as _;
use opentelemetry::logs::{Logger, LoggerProvider as _};
- use opentelemetry::InstrumentationLibrary;
- use opentelemetry::Key;
use opentelemetry::{logs::LogResult, KeyValue};
+ use opentelemetry::{InstrumentationScope, Key};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -794,8 +793,8 @@ mod tests {
runtime::Tokio,
);
- let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let mut record = LogRecord::default();
+ let instrumentation = InstrumentationScope::default();
processor.emit(&mut record, &instrumentation);
processor.force_flush().unwrap();
@@ -813,7 +812,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -883,11 +882,11 @@ mod tests {
#[derive(Debug)]
struct FirstProcessor {
- pub(crate) logs: Arc>>,
+ pub(crate) logs: Arc>>,
}
impl LogProcessor for FirstProcessor {
- fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationLibrary) {
+ fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationScope) {
// add attribute
record.add_attribute(
Key::from_static_str("processed_by"),
@@ -913,11 +912,11 @@ mod tests {
#[derive(Debug)]
struct SecondProcessor {
- pub(crate) logs: Arc>>,
+ pub(crate) logs: Arc>>,
}
impl LogProcessor for SecondProcessor {
- fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationLibrary) {
+ fn emit(&self, record: &mut LogRecord, instrumentation: &InstrumentationScope) {
assert!(record.attributes_contains(
&Key::from_static_str("processed_by"),
&AnyValue::String("FirstProcessor".into())
@@ -994,7 +993,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -1007,7 +1006,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -1024,7 +1023,7 @@ mod tests {
let processor_clone = Arc::clone(&processor);
let handle = tokio::spawn(async move {
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor_clone.emit(&mut record, &instrumentation);
});
handles.push(handle);
@@ -1043,7 +1042,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -1090,7 +1089,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
// This will panic because an tokio async operation within exporter without a runtime.
processor.emit(&mut record, &instrumentation);
@@ -1146,7 +1145,7 @@ mod tests {
let processor_clone = Arc::clone(&processor);
let handle = tokio::spawn(async move {
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor_clone.emit(&mut record, &instrumentation);
});
handles.push(handle);
@@ -1170,7 +1169,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -1189,7 +1188,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
@@ -1209,7 +1208,7 @@ mod tests {
let processor = SimpleLogProcessor::new(Box::new(exporter.clone()));
let mut record: LogRecord = Default::default();
- let instrumentation: InstrumentationLibrary = Default::default();
+ let instrumentation: InstrumentationScope = Default::default();
processor.emit(&mut record, &instrumentation);
diff --git a/opentelemetry-sdk/src/logs/mod.rs b/opentelemetry-sdk/src/logs/mod.rs
index 59b1b9b338..c01ed8c626 100644
--- a/opentelemetry-sdk/src/logs/mod.rs
+++ b/opentelemetry-sdk/src/logs/mod.rs
@@ -8,16 +8,16 @@ pub use log_processor::{
BatchConfig, BatchConfigBuilder, BatchLogProcessor, BatchLogProcessorBuilder, LogProcessor,
SimpleLogProcessor,
};
+use opentelemetry::InstrumentationScope;
pub use record::{LogRecord, TraceContext};
-use opentelemetry::InstrumentationLibrary;
/// `LogData` represents a single log event without resource context.
#[derive(Clone, Debug)]
pub struct LogData {
/// Log record
pub record: LogRecord,
/// Instrumentation details for the emitter who produced this `LogEvent`.
- pub instrumentation: InstrumentationLibrary,
+ pub instrumentation: InstrumentationScope,
}
#[cfg(all(test, feature = "testing"))]
@@ -104,38 +104,17 @@ mod tests {
#[test]
fn logger_attributes() {
let provider = LoggerProvider::builder().build();
- let logger = provider
- .logger_builder("test_logger")
+ let scope = InstrumentationScope::builder("test_logger")
.with_schema_url("https://opentelemetry.io/schema/1.0.0")
.with_attributes(vec![(KeyValue::new("test_k", "test_v"))])
.build();
- let instrumentation_library = logger.instrumentation_library();
- let attributes = &instrumentation_library.attributes;
- assert_eq!(instrumentation_library.name, "test_logger");
- assert_eq!(
- instrumentation_library.schema_url,
- Some("https://opentelemetry.io/schema/1.0.0".into())
- );
- assert_eq!(attributes.len(), 1);
- assert_eq!(attributes[0].key, "test_k".into());
- assert_eq!(attributes[0].value, "test_v".into());
- }
- #[test]
- #[allow(deprecated)]
- fn versioned_logger_options() {
- let provider = LoggerProvider::builder().build();
- let logger = provider.versioned_logger(
- "test_logger",
- Some("v1.2.3".into()),
- Some("https://opentelemetry.io/schema/1.0.0".into()),
- Some(vec![(KeyValue::new("test_k", "test_v"))]),
- );
- let instrumentation_library = logger.instrumentation_library();
- let attributes = &instrumentation_library.attributes;
- assert_eq!(instrumentation_library.version, Some("v1.2.3".into()));
+ let logger = provider.logger_with_scope(scope);
+ let instrumentation_scope = logger.instrumentation_scope();
+ let attributes = &instrumentation_scope.attributes;
+ assert_eq!(instrumentation_scope.name, "test_logger");
assert_eq!(
- instrumentation_library.schema_url,
+ instrumentation_scope.schema_url,
Some("https://opentelemetry.io/schema/1.0.0".into())
);
assert_eq!(attributes.len(), 1);
diff --git a/opentelemetry-sdk/src/metrics/data/mod.rs b/opentelemetry-sdk/src/metrics/data/mod.rs
index c7512bdc04..83b8ed5e97 100644
--- a/opentelemetry-sdk/src/metrics/data/mod.rs
+++ b/opentelemetry-sdk/src/metrics/data/mod.rs
@@ -2,9 +2,9 @@
use std::{any, borrow::Cow, fmt, time::SystemTime};
-use opentelemetry::KeyValue;
+use opentelemetry::{InstrumentationScope, KeyValue};
-use crate::{instrumentation::Scope, Resource};
+use crate::Resource;
pub use self::temporality::Temporality;
@@ -15,15 +15,15 @@ mod temporality;
pub struct ResourceMetrics {
/// The entity that collected the metrics.
pub resource: Resource,
- /// The collection of metrics with unique [Scope]s.
+ /// The collection of metrics with unique [InstrumentationScope]s.
pub scope_metrics: Vec,
}
/// A collection of metrics produced by a meter.
#[derive(Default, Debug)]
pub struct ScopeMetrics {
- /// The [Scope] that the meter was created with.
- pub scope: Scope,
+ /// The [InstrumentationScope] that the meter was created with.
+ pub scope: InstrumentationScope,
/// The list of aggregations created by the meter.
pub metrics: Vec,
}
diff --git a/opentelemetry-sdk/src/metrics/instrument.rs b/opentelemetry-sdk/src/metrics/instrument.rs
index b84fabbd3a..c2b3ce5219 100644
--- a/opentelemetry-sdk/src/metrics/instrument.rs
+++ b/opentelemetry-sdk/src/metrics/instrument.rs
@@ -2,13 +2,10 @@ use std::{borrow::Cow, collections::HashSet, sync::Arc};
use opentelemetry::{
metrics::{AsyncInstrument, SyncInstrument},
- Key, KeyValue,
+ InstrumentationScope, Key, KeyValue,
};
-use crate::{
- instrumentation::Scope,
- metrics::{aggregation::Aggregation, internal::Measure},
-};
+use crate::metrics::{aggregation::Aggregation, internal::Measure};
use super::data::Temporality;
@@ -96,7 +93,7 @@ pub struct Instrument {
/// Unit is the unit of measurement recorded by the instrument.
pub unit: Cow<'static, str>,
/// The instrumentation that created the instrument.
- pub scope: Scope,
+ pub scope: InstrumentationScope,
}
impl Instrument {
@@ -124,7 +121,7 @@ impl Instrument {
}
/// Set the instrument scope.
- pub fn scope(mut self, scope: Scope) -> Self {
+ pub fn scope(mut self, scope: InstrumentationScope) -> Self {
self.scope = scope;
self
}
@@ -135,7 +132,7 @@ impl Instrument {
&& self.description == ""
&& self.kind.is_none()
&& self.unit == ""
- && self.scope == Scope::default()
+ && self.scope == InstrumentationScope::default()
}
pub(crate) fn matches(&self, other: &Instrument) -> bool {
diff --git a/opentelemetry-sdk/src/metrics/meter.rs b/opentelemetry-sdk/src/metrics/meter.rs
index 8cab6e1b68..1a5432f000 100644
--- a/opentelemetry-sdk/src/metrics/meter.rs
+++ b/opentelemetry-sdk/src/metrics/meter.rs
@@ -8,10 +8,9 @@ use opentelemetry::{
InstrumentProvider, MetricsError, ObservableCounter, ObservableGauge,
ObservableUpDownCounter, Result, UpDownCounter,
},
- otel_error,
+ otel_error, InstrumentationScope,
};
-use crate::instrumentation::Scope;
use crate::metrics::{
instrument::{Instrument, InstrumentKind, Observable, ResolvedMeasures},
internal::{self, Number},
@@ -46,7 +45,7 @@ const INSTRUMENT_UNIT_INVALID_CHAR: &str = "characters in instrument unit must b
///
/// [Meter API]: opentelemetry::metrics::Meter
pub(crate) struct SdkMeter {
- scope: Scope,
+ scope: InstrumentationScope,
pipes: Arc,
u64_resolver: Resolver,
i64_resolver: Resolver,
@@ -54,7 +53,7 @@ pub(crate) struct SdkMeter {
}
impl SdkMeter {
- pub(crate) fn new(scope: Scope, pipes: Arc) -> Self {
+ pub(crate) fn new(scope: InstrumentationScope, pipes: Arc) -> Self {
let view_cache = Default::default();
SdkMeter {
@@ -179,19 +178,30 @@ impl SdkMeter {
{
let validation_result = validate_instrument_config(builder.name.as_ref(), &builder.unit);
if let Err(err) = validation_result {
- global::handle_error(err);
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable updown counter will not be invoked.",
+ reason = format!("{}", err));
return ObservableUpDownCounter::new();
}
match resolver.measures(
InstrumentKind::ObservableUpDownCounter,
- builder.name,
+ builder.name.clone(),
builder.description,
builder.unit,
None,
) {
Ok(ms) => {
if ms.is_empty() {
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable updown counter will not be invoked. Check View Configuration."
+ );
return ObservableUpDownCounter::new();
}
@@ -206,7 +216,12 @@ impl SdkMeter {
ObservableUpDownCounter::new()
}
Err(err) => {
- global::handle_error(err);
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable updown counter will not be invoked.",
+ reason = format!("{}", err));
ObservableUpDownCounter::new()
}
}
@@ -222,19 +237,30 @@ impl SdkMeter {
{
let validation_result = validate_instrument_config(builder.name.as_ref(), &builder.unit);
if let Err(err) = validation_result {
- global::handle_error(err);
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable gauge will not be invoked.",
+ reason = format!("{}", err));
return ObservableGauge::new();
}
match resolver.measures(
InstrumentKind::ObservableGauge,
- builder.name,
+ builder.name.clone(),
builder.description,
builder.unit,
None,
) {
Ok(ms) => {
if ms.is_empty() {
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable gauge will not be invoked. Check View Configuration."
+ );
return ObservableGauge::new();
}
@@ -249,7 +275,12 @@ impl SdkMeter {
ObservableGauge::new()
}
Err(err) => {
- global::handle_error(err);
+ otel_error!(
+ name: "InstrumentCreationFailed",
+ meter_name = self.scope.name.as_ref(),
+ instrument_name = builder.name.as_ref(),
+ message = "Callbacks for this observable gauge will not be invoked.",
+ reason = format!("{}", err));
ObservableGauge::new()
}
}
diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs
index c91773434b..2450328401 100644
--- a/opentelemetry-sdk/src/metrics/meter_provider.rs
+++ b/opentelemetry-sdk/src/metrics/meter_provider.rs
@@ -9,10 +9,10 @@ use std::{
use opentelemetry::{
metrics::{Meter, MeterProvider, MetricsError, Result},
- otel_debug, otel_error, KeyValue,
+ otel_debug, otel_error, InstrumentationScope,
};
-use crate::{instrumentation::Scope, Resource};
+use crate::Resource;
use super::{
meter::SdkMeter, noop::NoopMeter, pipeline::Pipelines, reader::MetricReader, view::View,
@@ -36,7 +36,7 @@ pub struct SdkMeterProvider {
#[derive(Debug)]
struct SdkMeterProviderInner {
pipes: Arc,
- meters: Mutex>>,
+ meters: Mutex>>,
is_shutdown: AtomicBool,
}
@@ -151,32 +151,24 @@ impl Drop for SdkMeterProviderInner {
}
}
+/// Default meter name if empty string is provided.
+const DEFAULT_COMPONENT_NAME: &str = "rust.opentelemetry.io/sdk/meter";
+
impl MeterProvider for SdkMeterProvider {
- fn versioned_meter(
- &self,
- name: &'static str,
- version: Option<&'static str>,
- schema_url: Option<&'static str>,
- attributes: Option>,
- ) -> Meter {
- if self.inner.is_shutdown.load(Ordering::Relaxed) {
- return Meter::new(Arc::new(NoopMeter::new()));
- }
+ fn meter(&self, mut name: &'static str) -> Meter {
+ if name.is_empty() {
+ name = DEFAULT_COMPONENT_NAME
+ };
- let mut builder = Scope::builder(name);
+ let scope = InstrumentationScope::builder(name).build();
+ self.meter_with_scope(scope)
+ }
- if let Some(v) = version {
- builder = builder.with_version(v);
- }
- if let Some(s) = schema_url {
- builder = builder.with_schema_url(s);
- }
- if let Some(a) = attributes {
- builder = builder.with_attributes(a);
+ fn meter_with_scope(&self, scope: InstrumentationScope) -> Meter {
+ if self.inner.is_shutdown.load(Ordering::Relaxed) {
+ return Meter::new(Arc::new(NoopMeter::new()));
}
- let scope = builder.build();
-
if let Ok(mut meters) = self.inner.meters.lock() {
let meter = meters
.entry(scope)
@@ -267,8 +259,8 @@ mod tests {
};
use crate::testing::metrics::metric_reader::TestMetricReader;
use crate::Resource;
- use opentelemetry::global;
use opentelemetry::metrics::MeterProvider;
+ use opentelemetry::{global, InstrumentationScope};
use opentelemetry::{Key, KeyValue, Value};
use std::env;
@@ -461,21 +453,31 @@ mod tests {
let _meter1 = provider.meter("test");
let _meter2 = provider.meter("test");
assert_eq!(provider.inner.meters.lock().unwrap().len(), 1);
- let _meter3 =
- provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);
- let _meter4 =
- provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);
- let _meter5 =
- provider.versioned_meter("test", Some("1.0.0"), Some("http://example.com"), None);
+
+ let scope = InstrumentationScope::builder("test")
+ .with_version("1.0.0")
+ .with_schema_url("http://example.com")
+ .build();
+
+ let _meter3 = provider.meter_with_scope(scope.clone());
+ let _meter4 = provider.meter_with_scope(scope.clone());
+ let _meter5 = provider.meter_with_scope(scope);
assert_eq!(provider.inner.meters.lock().unwrap().len(), 2);
- // the below are different meters, as meter names are case sensitive
- let _meter6 =
- provider.versioned_meter("ABC", Some("1.0.0"), Some("http://example.com"), None);
- let _meter7 =
- provider.versioned_meter("Abc", Some("1.0.0"), Some("http://example.com"), None);
- let _meter8 =
- provider.versioned_meter("abc", Some("1.0.0"), Some("http://example.com"), None);
+ // these are different meters because meter names are case sensitive
+ let mut library = InstrumentationScope::builder("ABC")
+ .with_version("1.0.0")
+ .with_schema_url("http://example.com")
+ .build();
+
+ let _meter6 = provider.meter_with_scope(library.clone());
+
+ library.name = "Abc".into();
+ let _meter7 = provider.meter_with_scope(library.clone());
+
+ library.name = "abc".into();
+ let _meter8 = provider.meter_with_scope(library);
+
assert_eq!(provider.inner.meters.lock().unwrap().len(), 5);
}
}
diff --git a/opentelemetry-sdk/src/metrics/mod.rs b/opentelemetry-sdk/src/metrics/mod.rs
index f2ac7a1a3d..d161d1846b 100644
--- a/opentelemetry-sdk/src/metrics/mod.rs
+++ b/opentelemetry-sdk/src/metrics/mod.rs
@@ -134,6 +134,7 @@ mod tests {
use crate::testing::metrics::InMemoryMetricsExporterBuilder;
use crate::{runtime, testing::metrics::InMemoryMetricsExporter};
use opentelemetry::metrics::{Counter, Meter, UpDownCounter};
+ use opentelemetry::InstrumentationScope;
use opentelemetry::{metrics::MeterProvider as _, KeyValue};
use rand::{rngs, Rng, SeedableRng};
use std::borrow::Cow;
@@ -637,18 +638,17 @@ mod tests {
// Act
// Meters are identical except for scope attributes, but scope attributes are not an identifying property.
// Hence there should be a single metric stream output for this test.
- let meter1 = meter_provider.versioned_meter(
- "test.meter",
- Some("v0.1.0"),
- Some("schema_url"),
- Some(vec![KeyValue::new("key", "value1")]),
- );
- let meter2 = meter_provider.versioned_meter(
- "test.meter",
- Some("v0.1.0"),
- Some("schema_url"),
- Some(vec![KeyValue::new("key", "value2")]),
- );
+ let mut scope = InstrumentationScope::builder("test.meter")
+ .with_version("v0.1.0")
+ .with_schema_url("http://example.com")
+ .with_attributes(vec![KeyValue::new("key", "value1")])
+ .build();
+
+ let meter1 = meter_provider.meter_with_scope(scope.clone());
+
+ scope.attributes = vec![KeyValue::new("key", "value2")];
+ let meter2 = meter_provider.meter_with_scope(scope);
+
let counter1 = meter1
.u64_counter("my_counter")
.with_unit("my_unit")
@@ -684,7 +684,7 @@ mod tests {
let scope = &resource_metrics[0].scope_metrics[0].scope;
assert_eq!(scope.name, "test.meter");
assert_eq!(scope.version, Some(Cow::Borrowed("v0.1.0")));
- assert_eq!(scope.schema_url, Some(Cow::Borrowed("schema_url")));
+ assert_eq!(scope.schema_url, Some(Cow::Borrowed("http://example.com")));
// This is validating current behavior, but it is not guaranteed to be the case in the future,
// as this is a user error and SDK reserves right to change this behavior.
diff --git a/opentelemetry-sdk/src/metrics/periodic_reader.rs b/opentelemetry-sdk/src/metrics/periodic_reader.rs
index 4f565bedb0..bebac2cff5 100644
--- a/opentelemetry-sdk/src/metrics/periodic_reader.rs
+++ b/opentelemetry-sdk/src/metrics/periodic_reader.rs
@@ -12,9 +12,8 @@ use futures_util::{
StreamExt,
};
use opentelemetry::{
- global,
metrics::{MetricsError, Result},
- otel_error,
+ otel_debug, otel_error,
};
use crate::runtime::Runtime;
@@ -245,13 +244,7 @@ impl PeriodicReaderWorker