mecomp_core/
logger.rs

1use std::time::Instant;
2use std::{io::Write, sync::LazyLock};
3
4use env_logger::fmt::style::{RgbColor, Style};
5use log::{Record, info};
6#[cfg(feature = "otel_tracing")]
7use opentelemetry::trace::TracerProvider as _;
8#[cfg(feature = "otel_tracing")]
9use opentelemetry_otlp::WithExportConfig as _;
10#[cfg(feature = "otel_tracing")]
11use opentelemetry_sdk::Resource;
12#[cfg(feature = "otel_tracing")]
13use tracing_subscriber::Layer as _;
14#[cfg(any(feature = "otel_tracing", feature = "flame", feature = "tokio_console"))]
15use tracing_subscriber::layer::SubscriberExt as _;
16
17use crate::format_duration;
18
19// This will get initialized below.
20/// Returns the init [`Instant`]
21pub static INIT_INSTANT: LazyLock<Instant> = LazyLock::new(Instant::now);
22
23/// Returns the seconds since [`INIT_INSTANT`].
24#[cfg(not(tarpaulin_include))]
25#[inline]
26pub fn uptime() -> u64 {
27    INIT_INSTANT.elapsed().as_secs()
28}
29
30#[allow(clippy::module_name_repetitions)]
31/// Initializes the logger.
32///
33/// This enables console logging on all the internals of `Mecomp`.
34///
35/// Functionality is provided by [`log`].
36///
37/// The levels are:
38/// - ERROR
39/// - WARN
40/// - INFO
41/// - DEBUG
42/// - TRACE
43///
44/// # Panics
45/// This must only be called _once_.
46#[cfg(not(tarpaulin_include))]
47#[allow(clippy::missing_inline_in_public_items)]
48pub fn init_logger(filter: log::LevelFilter, log_file_path: Option<std::path::PathBuf>) {
49    // Initialize timer.
50    let now = LazyLock::force(&INIT_INSTANT);
51
52    // create a new log file (if enabled).
53    let log_file = log_file_path.map(|path| {
54        let path = if path.is_dir() {
55            path.join("mecomp.log")
56        } else {
57            path
58        };
59
60        std::fs::OpenOptions::new()
61            .create(true)
62            .append(true)
63            .open(path)
64            .expect("Failed to create log file")
65    });
66
67    // If `RUST_LOG` isn't set, override it and disables
68    // all library crate logs except for mecomp and its sub-crates.
69    let mut env = String::new();
70    match std::env::var("RUST_LOG") {
71        Ok(e) => {
72            unsafe {
73                // SAFETY: This is safe because this code runs before we start spawning threads.
74                std::env::set_var("RUST_LOG", &e);
75            }
76            env = e;
77        }
78        // SOMEDAY:
79        // Support frontend names without *mecomp*.
80        _ => unsafe {
81            // SAFETY: This is safe because this code runs before we start spawning threads.
82            std::env::set_var("RUST_LOG", format!("off,mecomp={filter}"));
83        },
84    }
85
86    env_logger::Builder::new()
87        .format(move |buf, record| {
88            let style = buf.default_level_style(record.level());
89            let (level_style, level) = match record.level() {
90                log::Level::Debug => (
91                    style
92                        .fg_color(Some(RgbColor::from((0, 0x80, 0x80)).into()))
93                        .bold(),
94                    "D",
95                ),
96                log::Level::Trace => (
97                    style
98                        .fg_color(Some(RgbColor::from((255, 0, 255)).into()))
99                        .bold(),
100                    "T",
101                ),
102                log::Level::Info => (
103                    style
104                        .fg_color(Some(RgbColor::from((255, 255, 255)).into()))
105                        .bold(),
106                    "I",
107                ),
108                log::Level::Warn => (
109                    style
110                        .fg_color(Some(RgbColor::from((255, 255, 0)).into()))
111                        .bold(),
112                    "W",
113                ),
114                log::Level::Error => (
115                    style
116                        .fg_color(Some(RgbColor::from((255, 0, 0)).into()))
117                        .bold(),
118                    "E",
119                ),
120            };
121
122            let dimmed_style = Style::default().dimmed();
123
124            let log_line = format!(
125                // Longest PATH in the repo: `storage/src/db/schemas/dynamic/query.rs` - `39` characters
126                // Longest file in the repo: `core/src/audio/mod.rs`                   - `4` digits
127                //
128                // Use `scripts/longest.sh` to find this.
129                //
130                //                                                                             Longest PATH ---|        |--- Longest file
131                //                                                                                             |        |
132                //                                                                                             v        v
133                "| {level_style}{level}{level_style:#} | {dimmed_style}{}{dimmed_style:#} | {dimmed_style}{: >39} @ {: <4}{dimmed_style:#} | {}",
134                format_duration(&now.elapsed()),
135                process_path_of(record),
136                record.line().unwrap_or_default(),
137                record.args(),
138            );
139            writeln!(buf, "{log_line}")?;
140
141            // Write to log file (if enabled).
142            if let Some(log_file) = &log_file {
143                let mut log_file = log_file.try_clone().expect("Failed to clone log file");
144
145                // Remove ANSI formatting from log line before writing to file.
146                let unformatted_log_line: String = log_line
147                    .replace(&level_style.render().to_string(), "")
148                    .replace(&dimmed_style.render().to_string(), "")
149                    .replace("\x1B[0m", "");
150
151                writeln!(log_file, "{unformatted_log_line}")?;
152                log_file.sync_all().expect("Failed to sync log file");
153            }
154
155            Ok(())
156        })
157        .write_style(env_logger::WriteStyle::Always)
158        .parse_default_env()
159        .init();
160
161    if env.is_empty() {
162        info!("Log Level (Flag) ... {filter}");
163    } else {
164        info!("Log Level (RUST_LOG) ... {env}");
165    }
166}
167
168/// In debug builds, we want file paths so that we can Ctrl+Click them in an IDE to open the relevant file.
169/// But in release, all we want is to be able to tell what module the log is coming from.
170///
171/// This function will behave differently depending on the build type in order to achieve this.
172///
173/// In debug builds, if we get an absolute file path for a mecomp file, we want to strip everything before the `mecomp/` part to keep things clean.
174fn process_path_of<'a>(record: &'a Record<'a>) -> &'a str {
175    #[cfg(debug_assertions)]
176    const DEBUG_BUILD: bool = true;
177    #[cfg(not(debug_assertions))]
178    const DEBUG_BUILD: bool = false;
179
180    let module_path = record.module_path();
181    let file_path = record.file();
182
183    match (DEBUG_BUILD, module_path, file_path) {
184        // In debug builds, if we get an absolute file path for a mecomp file, we want to strip everything before the `mecomp/` part to keep things clean.
185        // and in debug builds, we fall back to this if the file path is not available.
186        (true, _, Some(file)) | (false, None, Some(file)) => {
187            // if the file is an absolute path, strip everything before the `mecomp/` part
188            if file.contains("mecomp/") {
189                file.split("mecomp/").last().unwrap_or(file)
190            } else {
191                file
192            }
193        }
194        // in debug builds, we fallback to the module path if the file is not available
195        // and in release builds, we want to use the module path by default.
196        (true, Some(module), None) | (false, Some(module), _) => module,
197
198        // otherwise just use a fallback
199        (true | false, None, None) => "??",
200    }
201}
202
203/// Initializes the tracing layer.
204///
205/// # Panics
206///
207/// panics if the tracing layers cannot be initialized.
208#[must_use]
209#[allow(clippy::missing_inline_in_public_items)]
210pub fn init_tracing() -> impl tracing::Subscriber {
211    let subscriber = tracing_subscriber::registry();
212
213    #[cfg(feature = "flame")]
214    let (flame_layer, _guard) = tracing_flame::FlameLayer::with_file("tracing.folded").unwrap();
215    #[cfg(feature = "flame")]
216    let subscriber = subscriber.with(flame_layer);
217
218    #[cfg(not(feature = "verbose_tracing"))]
219    #[allow(unused_variables)]
220    let filter = tracing_subscriber::EnvFilter::builder()
221        .parse("off,mecomp=trace")
222        .unwrap();
223    #[cfg(feature = "verbose_tracing")]
224    #[allow(unused_variables)]
225    let filter = tracing_subscriber::EnvFilter::new("trace")
226        .add_directive("hyper=off".parse().unwrap())
227        .add_directive("opentelemetry=off".parse().unwrap())
228        .add_directive("tonic=off".parse().unwrap())
229        .add_directive("h2=off".parse().unwrap())
230        .add_directive("reqwest=off".parse().unwrap());
231
232    #[cfg(feature = "otel_tracing")]
233    unsafe {
234        // SAFETY: This is safe because this code runs before we start spawning threads.
235        std::env::set_var("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "12");
236    }
237    #[cfg(feature = "otel_tracing")]
238    let tracer = opentelemetry_sdk::trace::SdkTracerProvider::builder()
239        .with_batch_exporter(
240            opentelemetry_otlp::SpanExporter::builder()
241                .with_tonic()
242                .with_endpoint("http://localhost:4317")
243                .build()
244                .expect("Failed to build OTLP exporter"),
245        )
246        .with_id_generator(opentelemetry_sdk::trace::RandomIdGenerator::default())
247        .with_resource(Resource::builder().with_service_name("mecomp").build())
248        .build()
249        .tracer("mecomp");
250
251    #[cfg(feature = "otel_tracing")]
252    let subscriber = subscriber.with(
253        tracing_opentelemetry::layer()
254            .with_tracer(tracer)
255            .with_filter(filter),
256    );
257
258    #[cfg(feature = "tokio_console")]
259    let console_layer = console_subscriber::Builder::default()
260        .retention(std::time::Duration::from_secs(60 * 20)) // 20 minutes
261        .enable_self_trace(true)
262        .spawn();
263    #[cfg(feature = "tokio_console")]
264    let subscriber = subscriber.with(console_layer);
265
266    subscriber
267}