Line data Source code
1 : use tracing_opentelemetry::OpenTelemetryLayer;
2 : use tracing_subscriber::{
3 : filter::{EnvFilter, LevelFilter},
4 : prelude::*,
5 : };
6 :
7 : /// Initialize logging and OpenTelemetry tracing and exporter.
8 : ///
9 : /// Logging can be configured using `RUST_LOG` environment variable.
10 : ///
11 : /// OpenTelemetry is configured with OTLP/HTTP exporter. It picks up
12 : /// configuration from environment variables. For example, to change the
13 : /// destination, set `OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318`.
14 : /// See <https://opentelemetry.io/docs/reference/specification/sdk-environment-variables>
15 0 : pub async fn init() -> anyhow::Result<LoggingGuard> {
16 0 : let env_filter = EnvFilter::builder()
17 0 : .with_default_directive(LevelFilter::INFO.into())
18 0 : .from_env_lossy();
19 0 :
20 0 : let fmt_layer = tracing_subscriber::fmt::layer()
21 0 : .with_ansi(false)
22 0 : .with_writer(std::io::stderr)
23 0 : .with_target(false);
24 :
25 0 : let otlp_layer = tracing_utils::init_tracing("proxy")
26 0 : .await
27 0 : .map(OpenTelemetryLayer::new);
28 0 :
29 0 : tracing_subscriber::registry()
30 0 : .with(env_filter)
31 0 : .with(otlp_layer)
32 0 : .with(fmt_layer)
33 0 : .try_init()?;
34 :
35 0 : Ok(LoggingGuard)
36 0 : }
37 :
38 : pub struct LoggingGuard;
39 :
40 : impl Drop for LoggingGuard {
41 0 : fn drop(&mut self) {
42 0 : // Shutdown trace pipeline gracefully, so that it has a chance to send any
43 0 : // pending traces before we exit.
44 0 : tracing::info!("shutting down the tracing machinery");
45 0 : tracing_utils::shutdown_tracing();
46 0 : }
47 : }
|