TLA Line data Source code
1 : //! Helper functions to set up OpenTelemetry tracing.
2 : //!
3 : //! This comes in two variants, depending on whether you have a Tokio runtime available.
4 : //! If you do, call `init_tracing()`. It sets up the trace processor and exporter to use
5 : //! the current tokio runtime. If you don't have a runtime available, or you don't want
6 : //! to share the runtime with the tracing tasks, call `init_tracing_without_runtime()`
7 : //! instead. It sets up a dedicated single-threaded Tokio runtime for the tracing tasks.
8 : //!
9 : //! Example:
10 : //!
11 : //! ```rust,no_run
12 : //! use tracing_subscriber::prelude::*;
13 : //! use tracing_opentelemetry::OpenTelemetryLayer;
14 : //!
15 : //! #[tokio::main]
16 : //! async fn main() {
17 : //! // Set up logging to stderr
18 : //! let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
19 : //! .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
20 : //! let fmt_layer = tracing_subscriber::fmt::layer()
21 : //! .with_target(false)
22 : //! .with_writer(std::io::stderr);
23 : //!
24 : //! // Initialize OpenTelemetry. Exports tracing spans as OpenTelemetry traces
25 : //! let otlp_layer = tracing_utils::init_tracing("my_application").await.map(OpenTelemetryLayer::new);
26 : //!
27 : //! // Put it all together
28 : //! tracing_subscriber::registry()
29 : //! .with(env_filter)
30 : //! .with(otlp_layer)
31 : //! .with(fmt_layer)
32 : //! .init();
33 : //! }
34 : //! ```
35 :
36 : use opentelemetry::sdk::Resource;
37 : use opentelemetry::KeyValue;
38 : use opentelemetry_otlp::WithExportConfig;
39 : use opentelemetry_otlp::{OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT};
40 :
41 : pub use tracing_opentelemetry::OpenTelemetryLayer;
42 :
43 : pub mod http;
44 :
45 : /// Set up OpenTelemetry exporter, using configuration from environment variables.
46 : ///
47 : /// `service_name` is set as the OpenTelemetry 'service.name' resource (see
48 : /// <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service>)
49 : ///
50 : /// We try to follow the conventions for the environment variables specified in
51 : /// <https://opentelemetry.io/docs/reference/specification/sdk-environment-variables/>
52 : ///
53 : /// However, we only support a subset of those options:
54 : ///
55 : /// - OTEL_SDK_DISABLED is supported. The default is "false", meaning tracing
56 : /// is enabled by default. Set it to "true" to disable.
57 : ///
58 : /// - We use the OTLP exporter, with HTTP protocol. Most of the OTEL_EXPORTER_OTLP_*
59 : /// settings specified in
60 : /// <https://opentelemetry.io/docs/reference/specification/protocol/exporter/>
61 : /// are supported, as they are handled by the `opentelemetry-otlp` crate.
62 : /// Settings related to other exporters have no effect.
63 : ///
64 : /// - Some other settings are supported by the `opentelemetry` crate.
65 : ///
66 : /// If you need some other setting, please test if it works first. And perhaps
67 : /// add a comment in the list above to save the effort of testing for the next
68 : /// person.
69 : ///
70 : /// This doesn't block, but is marked as 'async' to hint that this must be called in
71 : /// asynchronous execution context.
72 CBC 17 : pub async fn init_tracing(service_name: &str) -> Option<opentelemetry::sdk::trace::Tracer> {
73 17 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
74 UBC 0 : return None;
75 CBC 17 : };
76 17 : Some(init_tracing_internal(service_name.to_string()))
77 17 : }
78 :
79 : /// Like `init_tracing`, but creates a separate tokio Runtime for the tracing
80 : /// tasks.
81 641 : pub fn init_tracing_without_runtime(
82 641 : service_name: &str,
83 641 : ) -> Option<opentelemetry::sdk::trace::Tracer> {
84 641 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
85 UBC 0 : return None;
86 CBC 641 : };
87 641 :
88 641 : // The opentelemetry batch processor and the OTLP exporter needs a Tokio
89 641 : // runtime. Create a dedicated runtime for them. One thread should be
90 641 : // enough.
91 641 : //
92 641 : // (Alternatively, instead of batching, we could use the "simple
93 641 : // processor", which doesn't need Tokio, and use "reqwest-blocking"
94 641 : // feature for the OTLP exporter, which also doesn't need Tokio. However,
95 641 : // batching is considered best practice, and also I have the feeling that
96 641 : // the non-Tokio codepaths in the opentelemetry crate are less used and
97 641 : // might be more buggy, so better to stay on the well-beaten path.)
98 641 : //
99 641 : // We leak the runtime so that it keeps running after we exit the
100 641 : // function.
101 641 : let runtime = Box::leak(Box::new(
102 641 : tokio::runtime::Builder::new_multi_thread()
103 641 : .enable_all()
104 641 : .thread_name("otlp runtime thread")
105 641 : .worker_threads(1)
106 641 : .build()
107 641 : .unwrap(),
108 641 : ));
109 641 : let _guard = runtime.enter();
110 641 :
111 641 : Some(init_tracing_internal(service_name.to_string()))
112 641 : }
113 :
114 658 : fn init_tracing_internal(service_name: String) -> opentelemetry::sdk::trace::Tracer {
115 658 : // Set up exporter from the OTEL_EXPORTER_* environment variables
116 658 : let mut exporter = opentelemetry_otlp::new_exporter().http().with_env();
117 658 :
118 658 : // XXX opentelemetry-otlp v0.18.0 has a bug in how it uses the
119 658 : // OTEL_EXPORTER_OTLP_ENDPOINT env variable. According to the
120 658 : // OpenTelemetry spec at
121 658 : // <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#endpoint-urls-for-otlphttp>,
122 658 : // the full exporter URL is formed by appending "/v1/traces" to the value
123 658 : // of OTEL_EXPORTER_OTLP_ENDPOINT. However, opentelemetry-otlp only does
124 658 : // that with the grpc-tonic exporter. Other exporters, like the HTTP
125 658 : // exporter, use the URL from OTEL_EXPORTER_OTLP_ENDPOINT as is, without
126 658 : // appending "/v1/traces".
127 658 : //
128 658 : // See https://github.com/open-telemetry/opentelemetry-rust/pull/950
129 658 : //
130 658 : // Work around that by checking OTEL_EXPORTER_OTLP_ENDPOINT, and setting
131 658 : // the endpoint url with the "/v1/traces" path ourselves. If the bug is
132 658 : // fixed in a later version, we can remove this code. But if we don't
133 658 : // remember to remove this, it won't do any harm either, as the crate will
134 658 : // just ignore the OTEL_EXPORTER_OTLP_ENDPOINT setting when the endpoint
135 658 : // is set directly with `with_endpoint`.
136 658 : if std::env::var(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT).is_err() {
137 658 : if let Ok(mut endpoint) = std::env::var(OTEL_EXPORTER_OTLP_ENDPOINT) {
138 UBC 0 : if !endpoint.ends_with('/') {
139 0 : endpoint.push('/');
140 0 : }
141 0 : endpoint.push_str("v1/traces");
142 0 : exporter = exporter.with_endpoint(endpoint);
143 CBC 658 : }
144 UBC 0 : }
145 :
146 : // Propagate trace information in the standard W3C TraceContext format.
147 CBC 658 : opentelemetry::global::set_text_map_propagator(
148 658 : opentelemetry::sdk::propagation::TraceContextPropagator::new(),
149 658 : );
150 658 :
151 658 : opentelemetry_otlp::new_pipeline()
152 658 : .tracing()
153 658 : .with_exporter(exporter)
154 658 : .with_trace_config(
155 658 : opentelemetry::sdk::trace::config().with_resource(Resource::new(vec![KeyValue::new(
156 658 : opentelemetry_semantic_conventions::resource::SERVICE_NAME,
157 658 : service_name,
158 658 : )])),
159 658 : )
160 658 : .install_batch(opentelemetry::runtime::Tokio)
161 658 : .expect("could not initialize opentelemetry exporter")
162 658 : }
163 :
164 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
165 : // pending traces before we exit.
166 658 : pub fn shutdown_tracing() {
167 658 : opentelemetry::global::shutdown_tracer_provider();
168 658 : }
|