|
1 |
| -use std::fmt; |
2 |
| -use std::io::Write; |
| 1 | +use std::{fmt, io::Write}; |
| 2 | + |
| 3 | +#[cfg(feature = "otel")] |
| 4 | +use once_cell::sync::Lazy; |
| 5 | +#[cfg(feature = "otel")] |
| 6 | +use opentelemetry_sdk::trace::Tracer; |
| 7 | +#[cfg(feature = "otel")] |
| 8 | +use tracing::Subscriber; |
| 9 | +#[cfg(feature = "otel")] |
| 10 | +use tracing_subscriber::{registry::LookupSpan, EnvFilter, Layer}; |
3 | 11 |
|
4 | 12 | use crate::currentprocess::{process, terminalsource};
|
5 | 13 |
|
@@ -71,3 +79,48 @@ pub(crate) fn debug_fmt(args: fmt::Arguments<'_>) {
|
71 | 79 | let _ = writeln!(t.lock());
|
72 | 80 | }
|
73 | 81 | }
|
| 82 | + |
| 83 | +/// A [`tracing::Subscriber`] [`Layer`][`tracing_subscriber::Layer`] that corresponds to Rustup's |
| 84 | +/// optional `opentelemetry` (a.k.a. `otel`) feature. |
| 85 | +#[cfg(feature = "otel")] |
| 86 | +pub fn telemetry<S>() -> impl Layer<S> |
| 87 | +where |
| 88 | + S: Subscriber + for<'span> LookupSpan<'span>, |
| 89 | +{ |
| 90 | + // NOTE: This reads from the real environment variables instead of `process().var_os()`. |
| 91 | + let env_filter = EnvFilter::try_from_default_env().unwrap_or(EnvFilter::new("INFO")); |
| 92 | + tracing_opentelemetry::layer() |
| 93 | + .with_tracer(TELEMETRY_DEFAULT_TRACER.clone()) |
| 94 | + .with_filter(env_filter) |
| 95 | +} |
| 96 | + |
| 97 | +/// The default `opentelemetry` tracer used across Rustup. |
| 98 | +/// |
| 99 | +/// # Note |
| 100 | +/// The initializer function will panic if not called within the context of a [`tokio`] runtime. |
| 101 | +#[cfg(feature = "otel")] |
| 102 | +static TELEMETRY_DEFAULT_TRACER: Lazy<Tracer> = Lazy::new(|| { |
| 103 | + use std::time::Duration; |
| 104 | + |
| 105 | + use opentelemetry::KeyValue; |
| 106 | + use opentelemetry_otlp::WithExportConfig; |
| 107 | + use opentelemetry_sdk::{ |
| 108 | + trace::{self, Sampler}, |
| 109 | + Resource, |
| 110 | + }; |
| 111 | + |
| 112 | + opentelemetry_otlp::new_pipeline() |
| 113 | + .tracing() |
| 114 | + .with_exporter( |
| 115 | + opentelemetry_otlp::new_exporter() |
| 116 | + .tonic() |
| 117 | + .with_timeout(Duration::from_secs(3)), |
| 118 | + ) |
| 119 | + .with_trace_config( |
| 120 | + trace::config() |
| 121 | + .with_sampler(Sampler::AlwaysOn) |
| 122 | + .with_resource(Resource::new(vec![KeyValue::new("service.name", "rustup")])), |
| 123 | + ) |
| 124 | + .install_batch(opentelemetry_sdk::runtime::Tokio) |
| 125 | + .expect("error installing `OtlpTracePipeline` in the current `tokio` runtime") |
| 126 | +}); |
0 commit comments