mecomp_core/
logger.rs

1use std::time::Instant;
2use std::{io::Write, sync::LazyLock};
3
4use env_logger::fmt::style::{RgbColor, Style};
5use log::{info, Record};
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(any(feature = "otel_tracing", feature = "flame"))]
13use tracing_subscriber::layer::SubscriberExt as _;
14#[cfg(feature = "otel_tracing")]
15use tracing_subscriber::Layer 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        let log_file = std::fs::OpenOptions::new()
61            .create(true)
62            .append(true)
63            .open(path)
64            .expect("Failed to create log file");
65
66        log_file
67    });
68
69    // If `RUST_LOG` isn't set, override it and disables
70    // all library crate logs except for mecomp and its sub-crates.
71    let mut env = String::new();
72    #[allow(clippy::option_if_let_else)]
73    match std::env::var("RUST_LOG") {
74        Ok(e) => {
75            std::env::set_var("RUST_LOG", &e);
76            env = e;
77        }
78        // SOMEDAY:
79        // Support frontend names without *mecomp*.
80        _ => std::env::set_var("RUST_LOG", format!("off,mecomp={filter}")),
81    }
82
83    env_logger::Builder::new()
84        .format(move |buf, record| {
85            let style = buf.default_level_style(record.level());
86            let (level_style, level) = match record.level() {
87                log::Level::Debug => (
88                    style
89                        .fg_color(Some(RgbColor::from((0, 0x80, 0x80)).into()))
90                        .bold(),
91                    "D",
92                ),
93                log::Level::Trace => (
94                    style
95                        .fg_color(Some(RgbColor::from((255, 0, 255)).into()))
96                        .bold(),
97                    "T",
98                ),
99                log::Level::Info => (
100                    style
101                        .fg_color(Some(RgbColor::from((255, 255, 255)).into()))
102                        .bold(),
103                    "I",
104                ),
105                log::Level::Warn => (
106                    style
107                        .fg_color(Some(RgbColor::from((255, 255, 0)).into()))
108                        .bold(),
109                    "W",
110                ),
111                log::Level::Error => (
112                    style
113                        .fg_color(Some(RgbColor::from((255, 0, 0)).into()))
114                        .bold(),
115                    "E",
116                ),
117            };
118
119            let dimmed_style = Style::default().dimmed();
120
121            let log_line = format!(
122                // Longest PATH in the repo: `storage/src/db/schemas/dynamic/query.rs` - `39` characters
123                // Longest file in the repo: `core/src/audio/mod.rs`                   - `4` digits
124                //
125                // Use `scripts/longest.sh` to find this.
126                //
127                //                                                                             Longest PATH ---|        |--- Longest file
128                //                                                                                             |        |
129                //                                                                                             v        v
130                "| {level_style}{level}{level_style:#} | {dimmed_style}{}{dimmed_style:#} | {dimmed_style}{: >39} @ {: <4}{dimmed_style:#} | {}",
131                format_duration(&now.elapsed()),
132                process_path_of(record),
133                record.line().unwrap_or_default(),
134                record.args(),
135            );
136            writeln!(buf, "{log_line}")?;
137
138            // Write to log file (if enabled).
139            if let Some(log_file) = &log_file {
140                let mut log_file = log_file.try_clone().expect("Failed to clone log file");
141
142                // Remove ANSI formatting from log line before writing to file.
143                let unformatted_log_line: String = log_line
144                    .replace(&level_style.render().to_string(), "")
145                    .replace(&dimmed_style.render().to_string(), "")
146                    .replace("\x1B[0m", "");
147
148                writeln!(log_file, "{unformatted_log_line}")?;
149                log_file.sync_all().expect("Failed to sync log file");
150            }
151
152            Ok(())
153        })
154        .write_style(env_logger::WriteStyle::Always)
155        .parse_default_env()
156        .init();
157
158    if env.is_empty() {
159        info!("Log Level (Flag) ... {filter}");
160    } else {
161        info!("Log Level (RUST_LOG) ... {env}");
162    }
163}
164
165/// In debug builds, we want file paths so that we can Ctrl+Click them in an IDE to open the relevant file.
166/// But in release, all we want is to be able to tell what module the log is coming from.
167///
168/// This function will behave differently depending on the build type in order to achieve this.
169///
170/// 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.
171fn process_path_of<'a>(record: &'a Record<'a>) -> &'a str {
172    #[cfg(debug_assertions)]
173    const DEBUG_BUILD: bool = true;
174    #[cfg(not(debug_assertions))]
175    const DEBUG_BUILD: bool = false;
176
177    let module_path = record.module_path();
178    let file_path = record.file();
179
180    match (DEBUG_BUILD, module_path, file_path) {
181        // 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.
182        // and in debug builds, we fall back to this if the file path is not available.
183        (true, _, Some(file)) | (false, None, Some(file)) => {
184            // if the file is an absolute path, strip everything before the `mecomp/` part
185            if file.contains("mecomp/") {
186                file.split("mecomp/").last().unwrap_or(file)
187            } else {
188                file
189            }
190        }
191        // in debug builds, we fallback to the module path if the file is not available
192        // and in release builds, we want to use the module path by default.
193        (true, Some(module), None) | (false, Some(module), _) => module,
194
195        // otherwise just use a fallback
196        (true | false, None, None) => "??",
197    }
198}
199
200/// Initializes the tracing layer.
201///
202/// # Panics
203///
204/// panics if the tracing layers cannot be initialized.
205#[must_use]
206#[allow(clippy::missing_inline_in_public_items)]
207pub fn init_tracing() -> impl tracing::Subscriber {
208    let subscriber = tracing_subscriber::registry();
209
210    #[cfg(feature = "flame")]
211    let (flame_layer, _guard) = tracing_flame::FlameLayer::with_file("tracing.folded").unwrap();
212    #[cfg(feature = "flame")]
213    let subscriber = subscriber.with(flame_layer);
214
215    #[cfg(not(feature = "verbose_tracing"))]
216    #[allow(unused_variables)]
217    let filter = tracing_subscriber::EnvFilter::builder()
218        .parse("off,mecomp=trace")
219        .unwrap();
220    #[cfg(feature = "verbose_tracing")]
221    #[allow(unused_variables)]
222    let filter = tracing_subscriber::EnvFilter::new("trace")
223        .add_directive("hyper=off".parse().unwrap())
224        .add_directive("opentelemetry=off".parse().unwrap())
225        .add_directive("tonic=off".parse().unwrap())
226        .add_directive("h2=off".parse().unwrap())
227        .add_directive("reqwest=off".parse().unwrap());
228
229    #[cfg(feature = "otel_tracing")]
230    std::env::set_var("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "12");
231    #[cfg(feature = "otel_tracing")]
232    let tracer = opentelemetry_sdk::trace::SdkTracerProvider::builder()
233        .with_batch_exporter(
234            opentelemetry_otlp::SpanExporter::builder()
235                .with_tonic()
236                .with_endpoint("http://localhost:4317")
237                .build()
238                .expect("Failed to build OTLP exporter"),
239        )
240        .with_id_generator(opentelemetry_sdk::trace::RandomIdGenerator::default())
241        .with_resource(Resource::builder().with_service_name("mecomp").build())
242        .build()
243        .tracer("mecomp");
244
245    #[cfg(feature = "otel_tracing")]
246    let subscriber = subscriber.with(
247        tracing_opentelemetry::layer()
248            .with_tracer(tracer)
249            .with_filter(filter),
250    );
251
252    subscriber
253}