fedimint_logging/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4
5//! Constants for categorizing the logging type
6//!
7//! To help stabilize logging targets, avoid typos and improve consistency,
8//! it's preferable for logging statements use static target constants,
9//! that we define in this module.
10//!
11//! Core + server side components should use global namespace,
12//! while client should generally be prefixed with `client::`.
13//! This makes it easier to filter interesting calls when
14//! running e.g. `devimint`, that will run both server and client
15//! side.
16
17use std::fs::File;
18use std::{env, io};
19
20use tracing_subscriber::layer::SubscriberExt;
21use tracing_subscriber::util::SubscriberInitExt;
22use tracing_subscriber::{EnvFilter, Layer};
23
24pub const LOG_CONSENSUS: &str = "fm::consensus";
25pub const LOG_CORE: &str = "fm::core";
26pub const LOG_SERVER: &str = "fm::server";
27pub const LOG_DB: &str = "fm::db";
28pub const LOG_DEVIMINT: &str = "fm::devimint";
29pub const LOG_NET: &str = "fm::net";
30pub const LOG_NET_IROH: &str = "fm::net::iroh";
31pub const LOG_NET_WS: &str = "fm::net::ws";
32pub const LOG_NET_API: &str = "fm::net::api";
33pub const LOG_NET_PEER_DKG: &str = "fm::net::peer::dkg";
34pub const LOG_NET_PEER: &str = "fm::net::peer";
35pub const LOG_NET_AUTH: &str = "fm::net::auth";
36pub const LOG_TASK: &str = "fm::task";
37pub const LOG_RUNTIME: &str = "fm::runtime";
38pub const LOG_TEST: &str = "fm::test";
39pub const LOG_TIMING: &str = "fm::timing";
40pub const LOG_CLIENT: &str = "fm::client";
41pub const LOG_CLIENT_DB: &str = "fm::client::db";
42pub const LOG_CLIENT_EVENT_LOG: &str = "fm::client::event-log";
43pub const LOG_MODULE_MINT: &str = "fm::module::mint";
44pub const LOG_MODULE_META: &str = "fm::module::meta";
45pub const LOG_MODULE_WALLET: &str = "fm::module::wallet";
46pub const LOG_MODULE_LN: &str = "fm::module::ln";
47pub const LOG_MODULE_LNV2: &str = "fm::module::lnv2";
48pub const LOG_CLIENT_REACTOR: &str = "fm::client::reactor";
49pub const LOG_CLIENT_NET: &str = "fm::client::net";
50pub const LOG_CLIENT_NET_API: &str = "fm::client::net::api";
51pub const LOG_CLIENT_BACKUP: &str = "fm::client::backup";
52pub const LOG_CLIENT_RECOVERY: &str = "fm::client::recovery";
53pub const LOG_CLIENT_RECOVERY_MINT: &str = "fm::client::recovery::mint";
54pub const LOG_CLIENT_MODULE_MINT: &str = "fm::client::module::mint";
55pub const LOG_CLIENT_MODULE_META: &str = "fm::client::module::meta";
56pub const LOG_CLIENT_MODULE_LN: &str = "fm::client::module::ln";
57pub const LOG_CLIENT_MODULE_LNV2: &str = "fm::client::module::lnv2";
58pub const LOG_CLIENT_MODULE_WALLET: &str = "fm::client::module::wallet";
59pub const LOG_CLIENT_MODULE_GW: &str = "fm::client::module::gw";
60pub const LOG_CLIENT_MODULE_GWV2: &str = "fm::client::module::gwv2";
61pub const LOG_GATEWAY: &str = "fm::gw";
62pub const LOG_GATEWAY_UI: &str = "fm::gw::ui";
63pub const LOG_LIGHTNING: &str = "fm::gw::lightning";
64pub const LOG_BITCOIND_ESPLORA: &str = "fm::bitcoind::esplora";
65pub const LOG_BITCOIND_CORE: &str = "fm::bitcoind::bitcoincore";
66pub const LOG_BITCOIND: &str = "fm::bitcoind";
67pub const LOG_BITCOIN: &str = "fm::bitcoin";
68
69/// Consolidates the setup of server tracing into a helper
70#[derive(Default)]
71pub struct TracingSetup {
72    base_level: Option<String>,
73    extra_directives: Option<String>,
74    #[cfg(feature = "telemetry")]
75    tokio_console_bind: Option<std::net::SocketAddr>,
76    #[cfg(feature = "telemetry")]
77    with_jaeger: bool,
78    with_file: Option<File>,
79}
80
81impl TracingSetup {
82    /// Setup a console server for tokio logging <https://docs.rs/console-subscriber>
83    #[cfg(feature = "telemetry")]
84    pub fn tokio_console_bind(&mut self, address: Option<std::net::SocketAddr>) -> &mut Self {
85        self.tokio_console_bind = address;
86        self
87    }
88
89    /// Setup telemetry through Jaeger <https://docs.rs/tracing-jaeger>
90    #[cfg(feature = "telemetry")]
91    pub fn with_jaeger(&mut self, enabled: bool) -> &mut Self {
92        self.with_jaeger = enabled;
93        self
94    }
95
96    pub fn with_file(&mut self, file: Option<File>) -> &mut Self {
97        self.with_file = file;
98        self
99    }
100
101    /// Sets the log level applied to most modules. Some overly chatty modules
102    /// are muted even if this is set to a lower log level, use the `RUST_LOG`
103    /// environment variable to override.
104    pub fn with_base_level(&mut self, level: impl Into<String>) -> &mut Self {
105        self.base_level = Some(level.into());
106        self
107    }
108
109    /// Add a filter directive.
110    pub fn with_directive(&mut self, directive: &str) -> &mut Self {
111        if let Some(old) = self.extra_directives.as_mut() {
112            *old = format!("{old},{directive}");
113        } else {
114            self.extra_directives = Some(directive.to_owned());
115        }
116        self
117    }
118
119    /// Initialize the logging, must be called for tracing to begin
120    pub fn init(&mut self) -> anyhow::Result<()> {
121        use tracing_subscriber::fmt::writer::{BoxMakeWriter, Tee};
122
123        let var = env::var(tracing_subscriber::EnvFilter::DEFAULT_ENV).unwrap_or_default();
124        let filter_layer = EnvFilter::builder().parse(format!(
125            // We prefix everything with a default general log level and
126            // good per-module specific default. User provided RUST_LOG
127            // can override one or both
128            "{},{},{},{},{},{},{},{},{}",
129            self.base_level.as_deref().unwrap_or("info"),
130            "jsonrpsee_core::client::async_client=off",
131            "hyper=off",
132            "h2=off",
133            "jsonrpsee_server=warn,jsonrpsee_server::transport=off",
134            "AlephBFT-=error",
135            "iroh=error",
136            var,
137            self.extra_directives.as_deref().unwrap_or(""),
138        ))?;
139
140        let fmt_writer = match self.with_file.take() {
141            Some(file) => BoxMakeWriter::new(Tee::new(io::stderr, file)),
142            _ => BoxMakeWriter::new(io::stderr),
143        };
144
145        let fmt_layer = tracing_subscriber::fmt::layer()
146            .with_thread_names(false) // can be enabled for debugging
147            .with_writer(fmt_writer)
148            .with_filter(filter_layer);
149
150        let console_opt = || -> Option<Box<dyn Layer<_> + Send + Sync + 'static>> {
151            #[cfg(feature = "telemetry")]
152            if let Some(l) = self.tokio_console_bind {
153                let tracer = console_subscriber::ConsoleLayer::builder()
154                    .retention(std::time::Duration::from_secs(60))
155                    .server_addr(l)
156                    .spawn()
157                    // tokio-console cares only about these layers, so we filter separately for it
158                    .with_filter(EnvFilter::new("tokio=trace,runtime=trace"));
159                return Some(tracer.boxed());
160            }
161            None
162        };
163
164        let telemetry_layer_opt = || -> Option<Box<dyn Layer<_> + Send + Sync + 'static>> {
165            #[cfg(feature = "telemetry")]
166            if self.with_jaeger {
167                // TODO: https://github.com/fedimint/fedimint/issues/4591
168                #[allow(deprecated)]
169                let tracer = opentelemetry_jaeger::new_agent_pipeline()
170                    .with_service_name("fedimint")
171                    .install_simple()
172                    .unwrap();
173
174                return Some(tracing_opentelemetry::layer().with_tracer(tracer).boxed());
175            }
176            None
177        };
178
179        tracing_subscriber::registry()
180            .with(fmt_layer)
181            .with(console_opt())
182            .with(telemetry_layer_opt())
183            .try_init()?;
184        Ok(())
185    }
186}
187
188pub fn shutdown() {
189    #[cfg(feature = "telemetry")]
190    opentelemetry::global::shutdown_tracer_provider();
191}