Skip to main content

sp1_core_machine/utils/
logger.rs

1use std::{
2    sync::Once,
3    thread::{sleep, spawn},
4    time::Duration,
5};
6
7use sysinfo::{MemoryRefreshKind, RefreshKind, System};
8use tracing_forest::ForestLayer;
9use tracing_subscriber::{
10    fmt::format::FmtSpan, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry,
11};
12
13static INIT: Once = Once::new();
14
15#[allow(clippy::uninlined_format_args)]
16/// A simple logger.
17///
18/// Set the `RUST_LOG` environment variable to be set to `info` or `debug`.
19pub fn setup_logger() {
20    INIT.call_once(|| {
21        let env_filter = EnvFilter::try_from_default_env()
22            .unwrap_or_else(|_| EnvFilter::new("off"))
23            .add_directive("hyper=off".parse().unwrap())
24            .add_directive("slop_keccak_air=off".parse().unwrap())
25            .add_directive("p3_fri=off".parse().unwrap())
26            .add_directive("p3_dft=off".parse().unwrap())
27            .add_directive("p3_challenger=off".parse().unwrap());
28
29        // if the RUST_LOGGER environment variable is set, use it to determine which logger to
30        // configure (tracing_forest or tracing_subscriber)
31        // otherwise, default to 'forest'
32        let logger_type = std::env::var("RUST_LOGGER").unwrap_or_else(|_| "flat".to_string());
33        match logger_type.as_str() {
34            "forest" => {
35                Registry::default().with(env_filter).with(ForestLayer::default()).init();
36            }
37            "flat" => {
38                tracing_subscriber::fmt::Subscriber::builder()
39                    .compact()
40                    .with_file(false)
41                    .with_target(false)
42                    .with_thread_names(false)
43                    .with_env_filter(env_filter)
44                    .with_span_events(FmtSpan::CLOSE)
45                    .finish()
46                    .init();
47            }
48            _ => {
49                panic!("Invalid logger type: {logger_type}");
50            }
51        };
52
53        // Spawn a thread to warn when used memory is high
54        spawn(|| {
55            let mut sys = System::new_with_specifics(
56                RefreshKind::new().with_memory(MemoryRefreshKind::new().with_ram()),
57            );
58
59            let total_memory = sys.total_memory();
60
61            loop {
62                sleep(Duration::from_secs(10));
63                sys.refresh_memory();
64
65                let used_memory = sys.used_memory();
66                let ratio = used_memory as f64 / total_memory as f64;
67
68                if ratio > 0.8 {
69                    tracing::warn!(
70                        "Memory usage is high: {:.2}%, we recommend using the prover network",
71                        ratio * 100.0
72                    );
73                }
74            }
75        });
76    });
77}