Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade to opentelemetry 0.24 #155

Merged
merged 4 commits into from
Jul 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ jobs:
- name: install cargo-minimal-versions
uses: taiki-e/install-action@cargo-minimal-versions
- name: cargo minimal-versions check
working-directory: ${{ matrix.subcrate }}
run: cargo minimal-versions check --feature-powerset --no-dev-deps

### test jobs #############################################################
Expand Down
18 changes: 9 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"
djc marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -34,18 +34,18 @@ once_cell = "1.13.0"
# Fix minimal-versions
async-trait = { version = "0.1.56", optional = true }
futures-util = { version = "0.3.17", optional = true }
lazy_static = { version = "1.0.2", optional = true }
thiserror = { version = "1.0.31", optional = true }
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")
djc marked this conversation as resolved.
Show resolved Hide resolved
}

// 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
104 changes: 18 additions & 86 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 All @@ -591,35 +601,6 @@ where
}
}

/// Sets whether or not span and event metadata should include OpenTelemetry
/// exception fields such as `exception.message` and `exception.backtrace`
/// when an `Error` value is recorded. If multiple error values are recorded
/// on the same span/event, only the most recently recorded error value will
/// show up under these fields.
///
/// These attributes follow the [OpenTelemetry semantic conventions for
/// exceptions][conv].
///
/// By default, these attributes are recorded.
/// Note that this only works for `(dyn Error + 'static)`.
/// See [Implementations on Foreign Types of tracing::Value][impls] or [`OpenTelemetryLayer::with_error_events_to_exceptions`]
///
/// [conv]: https://github.com/open-telemetry/semantic-conventions/tree/main/docs/exceptions/
/// [impls]: https://docs.rs/tracing/0.1.37/tracing/trait.Value.html#foreign-impls
#[deprecated(
since = "0.21.0",
note = "renamed to `OpenTelemetryLayer::with_error_fields_to_exceptions`"
)]
pub fn with_exception_fields(self, exception_fields: bool) -> Self {
Self {
sem_conv_config: SemConvConfig {
error_fields_to_exceptions: exception_fields,
..self.sem_conv_config
},
..self
}
}

/// Sets whether or not span and event metadata should include OpenTelemetry
/// exception fields such as `exception.message` and `exception.backtrace`
/// when an `Error` value is recorded. If multiple error values are recorded
Expand Down Expand Up @@ -680,35 +661,6 @@ where
}
}

/// Sets whether or not reporting an `Error` value on an event will
/// propagate the OpenTelemetry exception fields such as `exception.message`
/// and `exception.backtrace` to the corresponding span. You do not need to
/// enable `with_exception_fields` in order to enable this. If multiple
/// error values are recorded on the same span/event, only the most recently
/// recorded error value will show up under these fields.
///
/// These attributes follow the [OpenTelemetry semantic conventions for
/// exceptions][conv].
///
/// By default, these attributes are propagated to the span. Note that this only works for `(dyn Error + 'static)`.
/// See [Implementations on Foreign Types of tracing::Value][impls] or [`OpenTelemetryLayer::with_error_events_to_exceptions`]
///
/// [conv]: https://github.com/open-telemetry/semantic-conventions/tree/main/docs/exceptions/
/// [impls]: https://docs.rs/tracing/0.1.37/tracing/trait.Value.html#foreign-impls
#[deprecated(
since = "0.21.0",
note = "renamed to `OpenTelemetryLayer::with_error_records_to_exceptions`"
)]
pub fn with_exception_field_propagation(self, exception_field_propagation: bool) -> Self {
Self {
sem_conv_config: SemConvConfig {
error_records_to_exceptions: exception_field_propagation,
..self.sem_conv_config
},
..self
}
}

/// Sets whether or not reporting an `Error` value on an event will
/// propagate the OpenTelemetry exception fields such as `exception.message`
/// and `exception.backtrace` to the corresponding span. You do not need to
Expand Down Expand Up @@ -747,26 +699,6 @@ where
Self { location, ..self }
}

/// Sets whether or not span and event metadata should include OpenTelemetry
/// attributes with location information, such as the file, module and line number.
///
/// These attributes follow the [OpenTelemetry semantic conventions for
/// source locations][conv].
///
/// By default, locations are enabled.
///
/// [conv]: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/general/attributes.md#source-code-attributes/
#[deprecated(
since = "0.17.3",
note = "renamed to `OpenTelemetrySubscriber::with_location`"
)]
pub fn with_event_location(self, event_location: bool) -> Self {
Self {
location: event_location,
..self
}
}

/// Sets whether or not spans metadata should include the _busy time_
/// (total time for which it was entered), and _idle time_ (total time
/// the span existed but was not entered).
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
Loading
Loading