Skip to content

Commit

Permalink
Upgrade to tracing-opentelemetry 0.24
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Jul 21, 2024
1 parent 70f6948 commit 83adbff
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 64 deletions.
17 changes: 8 additions & 9 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tracing-opentelemetry"
version = "0.24.0"
version = "0.25.0"
description = "OpenTelemetry integration for tracing"
homepage = "https://github.com/tokio-rs/tracing-opentelemetry"
repository = "https://github.com/tokio-rs/tracing-opentelemetry"
Expand All @@ -23,8 +23,8 @@ metrics = ["opentelemetry/metrics","opentelemetry_sdk/metrics", "smallvec"]
metrics_gauge_unstable = ["opentelemetry/otel_unstable"]

[dependencies]
opentelemetry = { version = "0.23.0", default-features = false, features = ["trace"] }
opentelemetry_sdk = { version = "0.23.0", default-features = false, features = ["trace"] }
opentelemetry = { version = "0.24", default-features = false, features = ["trace"] }
opentelemetry_sdk = { version = "0.24.1", default-features = false, features = ["trace"] }
tracing = { version = "0.1.35", default-features = false, features = ["std"] }
tracing-core = "0.1.28"
tracing-subscriber = { version = "0.3.0", default-features = false, features = ["registry", "std"] }
Expand All @@ -41,12 +41,11 @@ smallvec = { version = "1.0", optional = true }
[dev-dependencies]
async-trait = "0.1.56"
criterion = { version = "0.5.1", default-features = false, features = ["html_reports"] }
opentelemetry = { version = "0.23.0", features = ["trace", "metrics"] }
opentelemetry_sdk = { version = "0.23.0", default-features = false, features = ["trace", "rt-tokio"] }
opentelemetry-jaeger = "0.22.0"
opentelemetry-stdout = { version = "0.4.0", features = ["trace", "metrics"] }
opentelemetry-otlp = { version = "0.16.0", features = ["metrics"] }
opentelemetry-semantic-conventions = "0.15.0"
opentelemetry = { version = "0.24", features = ["trace", "metrics"] }
opentelemetry_sdk = { version = "0.24", default-features = false, features = ["trace", "rt-tokio"] }
opentelemetry-stdout = { version = "0.5", features = ["trace", "metrics"] }
opentelemetry-otlp = { version = "0.17", features = ["metrics"] }
opentelemetry-semantic-conventions = "0.16"
futures-util = { version = "0.3.17", default-features = false }
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
Expand Down
15 changes: 5 additions & 10 deletions benches/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use opentelemetry::{
trace::{Span, SpanBuilder, Tracer as _, TracerProvider as _},
Context,
};
use opentelemetry_sdk::trace::{Config, SpanLimits, Tracer, TracerProvider};
use opentelemetry_sdk::trace::{Config, Tracer, TracerProvider};
#[cfg(not(target_os = "windows"))]
use pprof::criterion::{Output, PProfProfiler};
use std::time::SystemTime;
Expand Down Expand Up @@ -160,15 +160,10 @@ fn many_events(c: &mut Criterion) {
}

{
let provider = TracerProvider::builder()
.with_config(Config {
span_limits: SpanLimits {
max_events_per_span: 1000,
..SpanLimits::default()
},
..Config::default()
})
.build();
let mut config = Config::default();
config.span_limits.max_events_per_span = 1000;

let provider = TracerProvider::builder().with_config(config).build();
let tracer = provider.tracer("bench");
let otel_layer = tracing_opentelemetry::layer()
.with_tracer(tracer)
Expand Down
4 changes: 2 additions & 2 deletions examples/opentelemetry-error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ impl Display for SpanData {
.as_secs()
)?;
writeln!(f, "- Resource:")?;
for (k, v) in self.0.resource.iter() {
writeln!(f, " - {}: {}", k, v)?;
for kv in self.0.attributes.iter() {
writeln!(f, " - {}: {}", kv.key, kv.value)?;
}
writeln!(f, "- Attributes:")?;
for kv in self.0.attributes.iter() {
Expand Down
12 changes: 8 additions & 4 deletions examples/opentelemetry-otlp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use opentelemetry::{global, Key, KeyValue};
use opentelemetry::{global, trace::TracerProvider, Key, KeyValue};
use opentelemetry_sdk::{
metrics::{
reader::{DefaultAggregationSelector, DefaultTemporalitySelector},
Expand Down Expand Up @@ -93,7 +93,7 @@ fn init_meter_provider() -> SdkMeterProvider {

// Construct Tracer for OpenTelemetryLayer
fn init_tracer() -> Tracer {
opentelemetry_otlp::new_pipeline()
let provider = opentelemetry_otlp::new_pipeline()
.tracing()
.with_trace_config(
opentelemetry_sdk::trace::Config::default()
Expand All @@ -108,20 +108,24 @@ fn init_tracer() -> Tracer {
.with_batch_config(BatchConfig::default())
.with_exporter(opentelemetry_otlp::new_exporter().tonic())
.install_batch(runtime::Tokio)
.unwrap()
.unwrap();

global::set_tracer_provider(provider.clone());
provider.tracer("tracing-otel-subscriber")
}

// Initialize tracing-subscriber and return OtelGuard for opentelemetry-related termination processing
fn init_tracing_subscriber() -> OtelGuard {
let meter_provider = init_meter_provider();
let tracer = init_tracer();

tracing_subscriber::registry()
.with(tracing_subscriber::filter::LevelFilter::from_level(
Level::INFO,
))
.with(tracing_subscriber::fmt::layer())
.with(MetricsLayer::new(meter_provider.clone()))
.with(OpenTelemetryLayer::new(init_tracer()))
.with(OpenTelemetryLayer::new(tracer))
.init();

OtelGuard { meter_provider }
Expand Down
26 changes: 18 additions & 8 deletions src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,13 +516,18 @@ where
/// ```no_run
/// use tracing_opentelemetry::OpenTelemetryLayer;
/// use tracing_subscriber::layer::SubscriberExt;
/// use opentelemetry::trace::TracerProvider;
/// use tracing_subscriber::Registry;
///
/// // Create a jaeger exporter pipeline for a `trace_demo` service.
/// let tracer = opentelemetry_jaeger::new_agent_pipeline()
/// .with_service_name("trace_demo")
/// // Create an OTLP pipeline exporter for a `trace_demo` service.
///
/// let otlp_exporter = opentelemetry_otlp::new_exporter().tonic();
/// let tracer = opentelemetry_otlp::new_pipeline()
/// .tracing()
/// .with_exporter(otlp_exporter)
/// .install_simple()
/// .expect("Error initializing Jaeger exporter");
/// .unwrap()
/// .tracer("trace_demo");
///
/// // Create a layer with the configured tracer
/// let otel_layer = OpenTelemetryLayer::new(tracer);
Expand Down Expand Up @@ -561,12 +566,17 @@ where
/// ```no_run
/// use tracing_subscriber::layer::SubscriberExt;
/// use tracing_subscriber::Registry;
/// use opentelemetry::trace::TracerProvider;
///
/// // Create an OTLP pipeline exporter for a `trace_demo` service.
///
/// // Create a jaeger exporter pipeline for a `trace_demo` service.
/// let tracer = opentelemetry_jaeger::new_agent_pipeline()
/// .with_service_name("trace_demo")
/// let otlp_exporter = opentelemetry_otlp::new_exporter().tonic();
/// let tracer = opentelemetry_otlp::new_pipeline()
/// .tracing()
/// .with_exporter(otlp_exporter)
/// .install_simple()
/// .expect("Error initializing Jaeger exporter");
/// .unwrap()
/// .tracer("trace_demo");
///
/// // Create a layer with the configured tracer
/// let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
Expand Down
27 changes: 10 additions & 17 deletions src/tracer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use opentelemetry::{
},
Context as OtelContext,
};
use opentelemetry_sdk::trace::{Tracer as SdkTracer, TracerProvider as SdkTracerProvider};
use opentelemetry_sdk::trace::{IdGenerator, Tracer as SdkTracer};

/// An interface for authors of OpenTelemetry SDKs to build pre-sampled tracers.
///
Expand Down Expand Up @@ -65,21 +65,18 @@ impl PreSampledTracer for noop::NoopTracer {

impl PreSampledTracer for SdkTracer {
fn sampled_context(&self, data: &mut crate::OtelData) -> OtelContext {
// Ensure tracing pipeline is still installed.
let Some(provider) = self.provider() else {
return OtelContext::new();
};
let parent_cx = &data.parent_cx;
let builder = &mut data.builder;

// Gather trace state
let (trace_id, parent_trace_flags) = current_trace_state(builder, parent_cx, &provider);
let (trace_id, parent_trace_flags) =
current_trace_state(builder, parent_cx, self.id_generator());

// Sample or defer to existing sampling decisions
let (flags, trace_state) = if let Some(result) = &builder.sampling_result {
process_sampling_result(result, parent_trace_flags)
} else {
builder.sampling_result = Some(provider.config().sampler.should_sample(
builder.sampling_result = Some(self.should_sample().should_sample(
Some(parent_cx),
trace_id,
&builder.name,
Expand All @@ -101,22 +98,18 @@ impl PreSampledTracer for SdkTracer {
}

fn new_trace_id(&self) -> otel::TraceId {
self.provider()
.map(|provider| provider.config().id_generator.new_trace_id())
.unwrap_or(otel::TraceId::INVALID)
self.id_generator().new_trace_id()
}

fn new_span_id(&self) -> otel::SpanId {
self.provider()
.map(|provider| provider.config().id_generator.new_span_id())
.unwrap_or(otel::SpanId::INVALID)
self.id_generator().new_span_id()
}
}

fn current_trace_state(
builder: &SpanBuilder,
parent_cx: &OtelContext,
provider: &SdkTracerProvider,
id_generator: &dyn IdGenerator,
) -> (TraceId, TraceFlags) {
if parent_cx.has_active_span() {
let span = parent_cx.span();
Expand All @@ -126,7 +119,7 @@ fn current_trace_state(
(
builder
.trace_id
.unwrap_or_else(|| provider.config().id_generator.new_trace_id()),
.unwrap_or_else(|| id_generator.new_trace_id()),
Default::default(),
)
}
Expand Down Expand Up @@ -159,7 +152,7 @@ mod tests {
use super::*;
use crate::OtelData;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::{config, Sampler, TracerProvider};
use opentelemetry_sdk::trace::{Config, Sampler, TracerProvider};

#[test]
fn assigns_default_trace_id_if_missing() {
Expand Down Expand Up @@ -203,7 +196,7 @@ mod tests {
fn sampled_context() {
for (name, sampler, parent_cx, previous_sampling_result, is_sampled) in sampler_data() {
let provider = TracerProvider::builder()
.with_config(config().with_sampler(sampler))
.with_config(Config::default().with_sampler(sampler))
.build();
let tracer = provider.tracer("test");
let mut builder = SpanBuilder::from_name("parent".to_string());
Expand Down
17 changes: 11 additions & 6 deletions tests/metrics_publishing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use opentelemetry_sdk::{
AggregationSelector, DefaultAggregationSelector, DefaultTemporalitySelector,
MetricReader, TemporalitySelector,
},
InstrumentKind, ManualReader, MeterProviderBuilder, SdkMeterProvider,
AttributeSet, InstrumentKind, ManualReader, MeterProviderBuilder, SdkMeterProvider,
},
AttributeSet, Resource,
Resource,
};

use std::{fmt::Debug, sync::Arc};
Expand Down Expand Up @@ -563,7 +563,12 @@ fn init_subscriber<T>(
expected_metric_name,
expected_instrument_kind,
expected_value,
expected_attributes,
expected_attributes: expected_attributes.map(|attrs| {
attrs
.iter()
.map(|(k, v)| KeyValue::new(k.clone(), v.clone()))
.collect()
}),
reader,
_meter_provider: provider.clone(),
};
Expand Down Expand Up @@ -613,7 +618,7 @@ struct TestExporter<T> {
expected_metric_name: String,
expected_instrument_kind: InstrumentKind,
expected_value: T,
expected_attributes: Option<AttributeSet>,
expected_attributes: Option<Vec<KeyValue>>,
reader: TestReader,
_meter_provider: SdkMeterProvider,
}
Expand Down Expand Up @@ -654,7 +659,7 @@ where

if let Some(expected_attributes) = self.expected_attributes.as_ref() {
sum.data_points.iter().for_each(|data_point| {
assert_eq!(expected_attributes, &data_point.attributes,)
assert_eq!(expected_attributes, &data_point.attributes)
});
}
}
Expand All @@ -672,7 +677,7 @@ where

if let Some(expected_attributes) = self.expected_attributes.as_ref() {
gauge.data_points.iter().for_each(|data_point| {
assert_eq!(expected_attributes, &data_point.attributes,)
assert_eq!(expected_attributes, &data_point.attributes)
});
}
}
Expand Down
16 changes: 8 additions & 8 deletions tests/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,18 @@ fn test_tracer() -> (
impl Subscriber + Clone,
) {
let exporter = TestExporter::default();
let mut config = Config::default();
config.span_limits = SpanLimits {
max_events_per_span: u32::MAX,
..SpanLimits::default()
};

let provider = TracerProvider::builder()
.with_simple_exporter(exporter.clone())
.with_config(Config {
span_limits: SpanLimits {
max_events_per_span: u32::MAX,
..SpanLimits::default()
},
..Config::default()
})
.with_config(config)
.build();
let tracer = provider.tracer("test");

let tracer = provider.tracer("test");
let subscriber = tracing_subscriber::registry()
.with(
layer()
Expand Down

0 comments on commit 83adbff

Please sign in to comment.