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 15 : pub async fn init_tracing(service_name: &str) -> Option<opentelemetry::sdk::trace::Tracer> {
73 15 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
74 0 : return None;
75 15 : };
76 15 : Some(init_tracing_internal(service_name.to_string()))
77 15 : }
78 :
79 : /// Like `init_tracing`, but creates a separate tokio Runtime for the tracing
80 : /// tasks.
81 663 : pub fn init_tracing_without_runtime(
82 663 : service_name: &str,
83 663 : ) -> Option<opentelemetry::sdk::trace::Tracer> {
84 663 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
85 0 : return None;
86 663 : };
87 663 :
88 663 : // The opentelemetry batch processor and the OTLP exporter needs a Tokio
89 663 : // runtime. Create a dedicated runtime for them. One thread should be
90 663 : // enough.
91 663 : //
92 663 : // (Alternatively, instead of batching, we could use the "simple
93 663 : // processor", which doesn't need Tokio, and use "reqwest-blocking"
94 663 : // feature for the OTLP exporter, which also doesn't need Tokio. However,
95 663 : // batching is considered best practice, and also I have the feeling that
96 663 : // the non-Tokio codepaths in the opentelemetry crate are less used and
97 663 : // might be more buggy, so better to stay on the well-beaten path.)
98 663 : //
99 663 : // We leak the runtime so that it keeps running after we exit the
100 663 : // function.
101 663 : let runtime = Box::leak(Box::new(
102 663 : tokio::runtime::Builder::new_multi_thread()
103 663 : .enable_all()
104 663 : .thread_name("otlp runtime thread")
105 663 : .worker_threads(1)
106 663 : .build()
107 663 : .unwrap(),
108 663 : ));
109 663 : let _guard = runtime.enter();
110 663 :
111 663 : Some(init_tracing_internal(service_name.to_string()))
112 663 : }
113 :
114 678 : fn init_tracing_internal(service_name: String) -> opentelemetry::sdk::trace::Tracer {
115 678 : // Set up exporter from the OTEL_EXPORTER_* environment variables
116 678 : let mut exporter = opentelemetry_otlp::new_exporter().http().with_env();
117 678 :
118 678 : // XXX opentelemetry-otlp v0.18.0 has a bug in how it uses the
119 678 : // OTEL_EXPORTER_OTLP_ENDPOINT env variable. According to the
120 678 : // OpenTelemetry spec at
121 678 : // <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#endpoint-urls-for-otlphttp>,
122 678 : // the full exporter URL is formed by appending "/v1/traces" to the value
123 678 : // of OTEL_EXPORTER_OTLP_ENDPOINT. However, opentelemetry-otlp only does
124 678 : // that with the grpc-tonic exporter. Other exporters, like the HTTP
125 678 : // exporter, use the URL from OTEL_EXPORTER_OTLP_ENDPOINT as is, without
126 678 : // appending "/v1/traces".
127 678 : //
128 678 : // See https://github.com/open-telemetry/opentelemetry-rust/pull/950
129 678 : //
130 678 : // Work around that by checking OTEL_EXPORTER_OTLP_ENDPOINT, and setting
131 678 : // the endpoint url with the "/v1/traces" path ourselves. If the bug is
132 678 : // fixed in a later version, we can remove this code. But if we don't
133 678 : // remember to remove this, it won't do any harm either, as the crate will
134 678 : // just ignore the OTEL_EXPORTER_OTLP_ENDPOINT setting when the endpoint
135 678 : // is set directly with `with_endpoint`.
136 678 : if std::env::var(OTEL_EXPORTER_OTLP_TRACES_ENDPOINT).is_err() {
137 678 : if let Ok(mut endpoint) = std::env::var(OTEL_EXPORTER_OTLP_ENDPOINT) {
138 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 678 : }
144 0 : }
145 :
146 : // Propagate trace information in the standard W3C TraceContext format.
147 678 : opentelemetry::global::set_text_map_propagator(
148 678 : opentelemetry::sdk::propagation::TraceContextPropagator::new(),
149 678 : );
150 678 :
151 678 : opentelemetry_otlp::new_pipeline()
152 678 : .tracing()
153 678 : .with_exporter(exporter)
154 678 : .with_trace_config(
155 678 : opentelemetry::sdk::trace::config().with_resource(Resource::new(vec![KeyValue::new(
156 678 : opentelemetry_semantic_conventions::resource::SERVICE_NAME,
157 678 : service_name,
158 678 : )])),
159 678 : )
160 678 : .install_batch(opentelemetry::runtime::Tokio)
161 678 : .expect("could not initialize opentelemetry exporter")
162 678 : }
163 :
164 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
165 : // pending traces before we exit.
166 678 : pub fn shutdown_tracing() {
167 678 : opentelemetry::global::shutdown_tracer_provider();
168 678 : }
|