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 tracing::Subscriber;
42 : use tracing_subscriber::registry::LookupSpan;
43 : use tracing_subscriber::Layer;
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 0 : pub async fn init_tracing<S>(service_name: &str) -> Option<impl Layer<S>>
73 0 : where
74 0 : S: Subscriber + for<'span> LookupSpan<'span>,
75 0 : {
76 0 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
77 0 : return None;
78 0 : };
79 0 : Some(init_tracing_internal(service_name.to_string()))
80 0 : }
81 :
82 : /// Like `init_tracing`, but creates a separate tokio Runtime for the tracing
83 : /// tasks.
84 0 : pub fn init_tracing_without_runtime<S>(service_name: &str) -> Option<impl Layer<S>>
85 0 : where
86 0 : S: Subscriber + for<'span> LookupSpan<'span>,
87 0 : {
88 0 : if std::env::var("OTEL_SDK_DISABLED") == Ok("true".to_string()) {
89 0 : return None;
90 0 : };
91 0 :
92 0 : // The opentelemetry batch processor and the OTLP exporter needs a Tokio
93 0 : // runtime. Create a dedicated runtime for them. One thread should be
94 0 : // enough.
95 0 : //
96 0 : // (Alternatively, instead of batching, we could use the "simple
97 0 : // processor", which doesn't need Tokio, and use "reqwest-blocking"
98 0 : // feature for the OTLP exporter, which also doesn't need Tokio. However,
99 0 : // batching is considered best practice, and also I have the feeling that
100 0 : // the non-Tokio codepaths in the opentelemetry crate are less used and
101 0 : // might be more buggy, so better to stay on the well-beaten path.)
102 0 : //
103 0 : // We leak the runtime so that it keeps running after we exit the
104 0 : // function.
105 0 : let runtime = Box::leak(Box::new(
106 0 : tokio::runtime::Builder::new_multi_thread()
107 0 : .enable_all()
108 0 : .thread_name("otlp runtime thread")
109 0 : .worker_threads(1)
110 0 : .build()
111 0 : .unwrap(),
112 0 : ));
113 0 : let _guard = runtime.enter();
114 0 :
115 0 : Some(init_tracing_internal(service_name.to_string()))
116 0 : }
117 :
118 0 : fn init_tracing_internal<S>(service_name: String) -> impl Layer<S>
119 0 : where
120 0 : S: Subscriber + for<'span> LookupSpan<'span>,
121 0 : {
122 0 : // Sets up exporter from the OTEL_EXPORTER_* environment variables.
123 0 : let exporter = opentelemetry_otlp::SpanExporter::builder()
124 0 : .with_http()
125 0 : .build()
126 0 : .expect("could not initialize opentelemetry exporter");
127 0 :
128 0 : // TODO: opentelemetry::global::set_error_handler() with custom handler that
129 0 : // bypasses default tracing layers, but logs regular looking log
130 0 : // messages.
131 0 :
132 0 : // Propagate trace information in the standard W3C TraceContext format.
133 0 : opentelemetry::global::set_text_map_propagator(
134 0 : opentelemetry_sdk::propagation::TraceContextPropagator::new(),
135 0 : );
136 0 :
137 0 : let tracer = opentelemetry_sdk::trace::TracerProvider::builder()
138 0 : .with_batch_exporter(exporter, opentelemetry_sdk::runtime::Tokio)
139 0 : .with_resource(opentelemetry_sdk::Resource::new(vec![KeyValue::new(
140 0 : opentelemetry_semantic_conventions::resource::SERVICE_NAME,
141 0 : service_name,
142 0 : )]))
143 0 : .build()
144 0 : .tracer("global");
145 0 :
146 0 : tracing_opentelemetry::layer().with_tracer(tracer)
147 0 : }
148 :
149 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
150 : // pending traces before we exit.
151 0 : pub fn shutdown_tracing() {
152 0 : opentelemetry::global::shutdown_tracer_provider();
153 0 : }
|