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 : //!
14 : //! #[tokio::main]
15 : //! async fn main() {
16 : //! // Set up logging to stderr
17 : //! let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
18 : //! .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));
19 : //! let fmt_layer = tracing_subscriber::fmt::layer()
20 : //! .with_target(false)
21 : //! .with_writer(std::io::stderr);
22 : //!
23 : //! // Initialize OpenTelemetry. Exports tracing spans as OpenTelemetry traces
24 : //! let otlp_layer = tracing_utils::init_tracing("my_application").await;
25 : //!
26 : //! // Put it all together
27 : //! tracing_subscriber::registry()
28 : //! .with(env_filter)
29 : //! .with(otlp_layer)
30 : //! .with(fmt_layer)
31 : //! .init();
32 : //! }
33 : //! ```
34 : #![deny(unsafe_code)]
35 : #![deny(clippy::undocumented_unsafe_blocks)]
36 :
37 : pub mod http;
38 :
39 : use opentelemetry::trace::TracerProvider;
40 : use opentelemetry::KeyValue;
41 : use opentelemetry_sdk::Resource;
42 : use tracing::Subscriber;
43 : use tracing_subscriber::registry::LookupSpan;
44 : use tracing_subscriber::Layer;
45 :
46 : /// Set up OpenTelemetry exporter, using configuration from environment variables.
47 : ///
48 : /// `service_name` is set as the OpenTelemetry 'service.name' resource (see
49 : /// <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service>)
50 : ///
51 : /// We try to follow the conventions for the environment variables specified in
52 : /// <https://opentelemetry.io/docs/reference/specification/sdk-environment-variables/>
53 : ///
54 : /// However, we only support a subset of those options:
55 : ///
56 : /// - OTEL_SDK_DISABLED is supported. The default is "false", meaning tracing
57 : /// is enabled by default. Set it to "true" to disable.
58 : ///
59 : /// - We use the OTLP exporter, with HTTP protocol. Most of the OTEL_EXPORTER_OTLP_*
60 : /// settings specified in
61 : /// <https://opentelemetry.io/docs/reference/specification/protocol/exporter/>
62 : /// are supported, as they are handled by the `opentelemetry-otlp` crate.
63 : /// Settings related to other exporters have no effect.
64 : ///
65 : /// - Some other settings are supported by the `opentelemetry` crate.
66 : ///
67 : /// If you need some other setting, please test if it works first. And perhaps
68 : /// add a comment in the list above to save the effort of testing for the next
69 : /// person.
70 : ///
71 : /// This doesn't block, but is marked as 'async' to hint that this must be called in
72 : /// asynchronous execution context.
73 0 : pub async fn init_tracing<S>(service_name: &str) -> Option<impl Layer<S>>
74 0 : where
75 0 : S: Subscriber + for<'span> LookupSpan<'span>,
76 0 : {
77 0 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
78 0 : return None;
79 0 : };
80 0 : Some(init_tracing_internal(service_name.to_string()))
81 0 : }
82 :
83 : /// Like `init_tracing`, but creates a separate tokio Runtime for the tracing
84 : /// tasks.
85 0 : pub fn init_tracing_without_runtime<S>(service_name: &str) -> Option<impl Layer<S>>
86 0 : where
87 0 : S: Subscriber + for<'span> LookupSpan<'span>,
88 0 : {
89 0 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
90 0 : return None;
91 0 : };
92 0 :
93 0 : // The opentelemetry batch processor and the OTLP exporter needs a Tokio
94 0 : // runtime. Create a dedicated runtime for them. One thread should be
95 0 : // enough.
96 0 : //
97 0 : // (Alternatively, instead of batching, we could use the "simple
98 0 : // processor", which doesn't need Tokio, and use "reqwest-blocking"
99 0 : // feature for the OTLP exporter, which also doesn't need Tokio. However,
100 0 : // batching is considered best practice, and also I have the feeling that
101 0 : // the non-Tokio codepaths in the opentelemetry crate are less used and
102 0 : // might be more buggy, so better to stay on the well-beaten path.)
103 0 : //
104 0 : // We leak the runtime so that it keeps running after we exit the
105 0 : // function.
106 0 : let runtime = Box::leak(Box::new(
107 0 : tokio::runtime::Builder::new_multi_thread()
108 0 : .enable_all()
109 0 : .thread_name("otlp runtime thread")
110 0 : .worker_threads(1)
111 0 : .build()
112 0 : .unwrap(),
113 0 : ));
114 0 : let _guard = runtime.enter();
115 0 :
116 0 : Some(init_tracing_internal(service_name.to_string()))
117 0 : }
118 :
119 0 : fn init_tracing_internal<S>(service_name: String) -> impl Layer<S>
120 0 : where
121 0 : S: Subscriber + for<'span> LookupSpan<'span>,
122 0 : {
123 0 : // Sets up exporter from the OTEL_EXPORTER_* environment variables.
124 0 : let exporter = opentelemetry_otlp::new_exporter().http();
125 0 :
126 0 : // TODO: opentelemetry::global::set_error_handler() with custom handler that
127 0 : // bypasses default tracing layers, but logs regular looking log
128 0 : // messages.
129 0 :
130 0 : // Propagate trace information in the standard W3C TraceContext format.
131 0 : opentelemetry::global::set_text_map_propagator(
132 0 : opentelemetry_sdk::propagation::TraceContextPropagator::new(),
133 0 : );
134 0 :
135 0 : let tracer = opentelemetry_otlp::new_pipeline()
136 0 : .tracing()
137 0 : .with_exporter(exporter)
138 0 : .with_trace_config(opentelemetry_sdk::trace::Config::default().with_resource(
139 0 : Resource::new(vec![KeyValue::new(
140 0 : opentelemetry_semantic_conventions::resource::SERVICE_NAME,
141 0 : service_name,
142 0 : )]),
143 0 : ))
144 0 : .install_batch(opentelemetry_sdk::runtime::Tokio)
145 0 : .expect("could not initialize opentelemetry exporter")
146 0 : .tracer("global");
147 0 :
148 0 : tracing_opentelemetry::layer().with_tracer(tracer)
149 0 : }
150 :
151 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
152 : // pending traces before we exit.
153 0 : pub fn shutdown_tracing() {
154 0 : opentelemetry::global::shutdown_tracer_provider();
155 0 : }
|