Skip to main content

wde_logger/
lib.rs

1//! Logging functions and configuration for WaterDropEngine using [`tracing`](https://docs.rs/tracing).
2//!
3//! The logging behavior can be configured using the [`LogPlugin`], which allows you to set the log level, filter logs using `EnvFilter` syntax, and add custom layers to the tracing subscriber. The `RUST_LOG` environment variable can also be used to override plugin settings and configure log filtering.
4//!
5//! This crate provides multiple macros for logging, including:
6//! - [`trace!()`](crate::trace) - Verbose tracing information, typically only useful for debugging.
7//! - [`debug!()`](crate::debug) - Debug information, useful for development and debugging.
8//! - [`info!()`](crate::info) - General information about the application's operation.
9//! - [`warn!()`](crate::warn) - Important warnings that may indicate potential issues.
10//! - [`error!()`](crate::error) - Critical errors that indicate failures in the application.
11//!
12//! Each of these macros also has a corresponding `_once` variant (e.g. [`info_once!()`](crate::info_once)) that will only log the message once per call site, which is useful for logging within systems that are called every frame without spamming the logs.
13//!
14//! Lastly, span tracing is supported using the `*_span!()` macros (e.g. [`info_span!()`](crate::info_span)) which can be used to create spans for better structuring of logs and performance profiling.
15
16pub mod editor_layer;
17mod panic_handler;
18mod panic_report_layer;
19mod puffin_layer;
20
21extern crate alloc;
22
23use core::error::Error;
24
25mod once;
26pub use once::OnceFlag;
27
28#[doc(hidden)]
29pub mod prelude {
30    pub use crate::LogLevel;
31    pub use crate::{debug_once, error_once, info_once, trace_once, warn_once};
32    pub use tracing::event;
33    pub use tracing::{
34        debug, debug_span, error, error_span, info, info_span, trace, trace_span, warn, warn_span
35    };
36}
37
38pub use tracing::{
39    self, Level as LogLevel, debug, debug_span, error, error_span, info, info_span, trace,
40    trace_span, warn, warn_span
41};
42
43use bevy::prelude::*;
44use tracing_log::LogTracer;
45use tracing_subscriber::{
46    EnvFilter, Layer,
47    filter::{FromEnvError, ParseError},
48    layer::Layered,
49    prelude::*,
50    registry::Registry
51};
52
53// Store the guard for the non-blocking file appender to ensure logs are flushed on drop and to prevent it from being dropped while the subscriber is still active.
54#[allow(dead_code)]
55#[derive(Resource)]
56struct LoggerGuard(tracing_appender::non_blocking::WorkerGuard);
57
58#[cfg(feature = "puffin")]
59use crate::puffin_layer::PuffinLayer;
60
61/// A boxed [`Layer`] that can be used with [`LogPlugin::custom_layer`].
62type BoxedLayer = Box<dyn Layer<Registry> + Send + Sync + 'static>;
63#[cfg(feature = "tracing")]
64type BaseSubscriber =
65    Layered<EnvFilter, Layered<Option<Box<dyn Layer<Registry> + Send + Sync>>, Registry>>;
66#[cfg(feature = "tracing")]
67type PreFmtSubscriber = Layered<tracing_error::ErrorLayer<BaseSubscriber>, BaseSubscriber>;
68#[cfg(not(feature = "tracing"))]
69type PreFmtSubscriber =
70    Layered<EnvFilter, Layered<Option<Box<dyn Layer<Registry> + Send + Sync>>, Registry>>;
71
72/// A boxed [`Layer`] that can be used with [`LogPlugin::fmt_layer`].
73type BoxedFmtLayer = Box<dyn Layer<PreFmtSubscriber> + Send + Sync + 'static>;
74
75/// Target prefix of the engine crates, logged at [`LogPlugin::level`].
76const ENGINE_TARGET: &str = "wde";
77
78/// Overrides for dependencies that are noisy at `INFO`.
79const DEFAULT_FILTER: &str = concat!(
80    "wgpu=warn,",
81    "wgpu_hal::vulkan::instance=error,",
82    "naga=warn,",
83    "egui_wgpu=error,",
84    "winit=warn,",
85    "calloop=warn,",
86    "cosmic_text=warn,",
87    "notify=warn,",
88    "notify_debouncer_full=warn"
89);
90
91/// Plugin that configures logging for WaterDropEngine applications.
92///
93/// # Configuration
94///
95/// The engine and the [`crates`](LogPlugin::crates) of the application are logged at
96/// [`level`](LogPlugin::level), every other dependency at `INFO` at most.
97///
98/// The `RUST_LOG` environment variable overrides plugin settings and uses [`EnvFilter`] syntax.
99/// Set `NO_COLOR=1` to disable colored output (see [no-color.org](https://no-color.org/)).
100///
101/// # Log Levels
102///
103/// Available log levels (most to least important):
104/// - `error!()` - Critical failures
105/// - `warn!()` - Important warnings
106/// - `info!()` - General information
107/// - `debug!()` - Debug information
108/// - `trace!()` - Verbose tracing
109pub struct LogPlugin {
110    /// Extra [`EnvFilter`] directives, applied after the levels.
111    pub filter: String,
112
113    /// Level of the engine and of [`crates`](LogPlugin::crates).
114    pub level: LogLevel,
115
116    /// Targets of the application crates (crate names with `-` replaced by `_`, matched as
117    /// prefixes), logged at [`level`](LogPlugin::level) like the engine.
118    pub crates: Vec<String>,
119
120    /// Optionally add an extra [`Layer`] to the tracing subscriber.
121    pub custom_layer: fn(app: &mut App) -> Option<BoxedLayer>,
122
123    /// Override the default [`tracing_subscriber::fmt::Layer`] with a custom one.
124    /// For example, you can use [`tracing_subscriber::fmt::Layer::without_time`] to remove the
125    /// timestamp from the log output.
126    pub fmt_layer: fn(app: &mut App) -> Option<BoxedFmtLayer>,
127
128    /// Path of the file logs are written to. The previous log file, if any, is renamed
129    /// alongside it with a `-old` suffix before its extension (e.g. `log.txt` -> `log-old.txt`).
130    ///
131    /// Defaults to `<temp_dir>/waterdropengine/log.txt`.
132    pub log_file: std::path::PathBuf
133}
134impl Default for LogPlugin {
135    fn default() -> Self {
136        Self {
137            filter: String::new(),
138            level: LogLevel::INFO,
139            crates: Vec::new(),
140            custom_layer: |_| None,
141            fmt_layer: |_| None,
142            log_file: std::env::temp_dir().join("waterdropengine").join("log.txt")
143        }
144    }
145}
146impl LogPlugin {
147    /// `DEBUG` in debug builds and `INFO` in release builds, overridden by the `--debug` and
148    /// `--trace` arguments.
149    pub fn auto_level(mut self) -> Self {
150        let args = std::env::args().collect::<Vec<_>>();
151        self.level = if args.iter().any(|arg| arg == "--trace") {
152            LogLevel::TRACE
153        } else if cfg!(debug_assertions) || args.iter().any(|arg| arg == "--debug") {
154            LogLevel::DEBUG
155        } else {
156            LogLevel::INFO
157        };
158        self
159    }
160
161    /// Full [`EnvFilter`] directives built from the plugin settings.
162    fn directives(&self) -> String {
163        let mut directives = format!(
164            "{},{ENGINE_TARGET}={}",
165            self.level.min(LogLevel::INFO),
166            self.level
167        );
168        for target in &self.crates {
169            directives.push_str(&format!(",{target}={}", self.level));
170        }
171        directives.push_str(&format!(",{DEFAULT_FILTER}"));
172        if !self.filter.is_empty() {
173            directives.push_str(&format!(",{}", self.filter));
174        }
175        directives
176    }
177
178    /// Overrides the log level of a crate/module target (e.g. `"bevy_asset"`), regardless of `level`.
179    pub fn with_crate_level(mut self, target: &str, level: LogLevel) -> Self {
180        if !self.filter.is_empty() {
181            self.filter.push(',');
182        }
183        self.filter.push_str(&format!("{target}={level}"));
184        self
185    }
186}
187impl Plugin for LogPlugin {
188    fn build(&self, app: &mut App) {
189        // Configure the panic hook
190        configure_panic_hook();
191
192        // Build the tracing subscriber with the configured layers and filters
193        let directives = self.directives();
194        let (subscriber, _guard) = configure_subscriber(
195            app,
196            &directives,
197            self.custom_layer,
198            self.fmt_layer,
199            &self.log_file
200        );
201        app.insert_resource(LoggerGuard(_guard));
202
203        // Set the global logger and subscriber based on the different features enabled
204        let logger_already_set = LogTracer::init().is_err();
205        let subscriber_already_set = tracing::subscriber::set_global_default(subscriber).is_err();
206
207        // Initial log message
208        info!("Starting WaterDropEngine.");
209        info!("Logs will be written to {}.", self.log_file.display());
210
211        // Log errors if we failed to set the global logger or subscriber, likely due to another logger/subscriber already being set.
212        match (logger_already_set, subscriber_already_set) {
213            (true, true) => error!(
214                "Could not set global logger and tracing subscriber as they are already set. Consider disabling LogPlugin."
215            ),
216            (true, false) => error!(
217                "Could not set global logger as it is already set. Consider disabling LogPlugin."
218            ),
219            (false, true) => error!(
220                "Could not set global tracing subscriber as it is already set. Consider disabling LogPlugin."
221            ),
222            (false, false) => ()
223        }
224        debug!("Log filter: {directives}.");
225
226        // Log warnings about features that may increase memory usage and potential conflicts with existing loggers/subscribers
227        #[cfg(feature = "tracing")]
228        warn!(
229            "Tracing with Tracy is active, memory consumption will grow until a client is connected."
230        );
231        #[cfg(feature = "puffin")]
232        debug!("Tracing with Puffin is active.");
233    }
234}
235
236fn configure_panic_hook() {
237    let custom_hook = panic_handler::PanicHook::get();
238    std::panic::set_hook(Box::new(move |infos| {
239        #[cfg(feature = "tracing")]
240        eprintln!("{}", tracing_error::SpanTrace::capture());
241        custom_hook(infos);
242    }));
243}
244
245fn configure_subscriber(
246    app: &mut App,
247    directives: &str,
248    custom_layer: fn(app: &mut App) -> Option<BoxedLayer>,
249    fmt_layer: fn(app: &mut App) -> Option<BoxedFmtLayer>,
250    log_file: &std::path::Path
251) -> (
252    impl tracing::Subscriber + Send + Sync,
253    tracing_appender::non_blocking::WorkerGuard
254) {
255    let subscriber = Registry::default();
256
257    // Add optional layer provided by user
258    let subscriber = subscriber.with((custom_layer)(app));
259
260    // Set up filter corresponding to the env variable RUST_LOG, or use the default filter if the env variable is not set or invalid
261    let default_filter = directives;
262    let filter_layer = EnvFilter::try_from_default_env()
263        .or_else(|from_env_error| {
264            _ = from_env_error
265                .source()
266                .and_then(|source| source.downcast_ref::<ParseError>())
267                .map(|parse_err| {
268                    // We cannot use the `error!` macro here because the logger is not ready yet.
269                    eprintln!("Invalid RUST_LOG environment variable: {parse_err}. Falling back to default filter: {default_filter}");
270                });
271            Ok::<EnvFilter, FromEnvError>(EnvFilter::builder().parse_lossy(default_filter))
272        })
273        .unwrap();
274    let subscriber = subscriber.with(filter_layer);
275
276    // Register default error layer for capturing backtraces if the `tracing` feature is enabled.
277    #[cfg(feature = "tracing")]
278    let subscriber = subscriber.with(tracing_error::ErrorLayer::default());
279
280    // Set up writer layer
281    let fmt_layer = {
282        // By default, use the default fmt layer with stderr as the output
283        let fmt_layer = (fmt_layer)(app).unwrap_or_else(|| {
284            Box::new(tracing_subscriber::fmt::Layer::default().with_writer(std::io::stderr))
285        });
286
287        // Ignore some logs when using tracy
288        #[cfg(feature = "tracing")]
289        let fmt_layer = fmt_layer.with_filter(tracing_subscriber::filter::FilterFn::new(|meta| {
290            meta.fields().field("tracy.frame_mark").is_none()
291        }));
292        fmt_layer
293    };
294    let subscriber = subscriber.with(fmt_layer);
295
296    // Keep an in-memory ring buffer of recent logs for panic reports.
297    let subscriber = subscriber.with(panic_report_layer::PanicReportLogLayer);
298
299    // Rename old log file
300    let path = log_file
301        .parent()
302        .unwrap_or_else(|| std::path::Path::new("."));
303    let _ = std::fs::create_dir_all(path);
304    let file_name = log_file
305        .file_name()
306        .unwrap_or_else(|| std::ffi::OsStr::new("log.txt"));
307    if log_file.exists() {
308        let archived_log_file = {
309            let stem = log_file.file_stem().unwrap_or(file_name).to_string_lossy();
310            let ext = log_file
311                .extension()
312                .map(|ext| format!(".{}", ext.to_string_lossy()))
313                .unwrap_or_default();
314            path.join(format!("{stem}-old{ext}"))
315        };
316        let _ = std::fs::rename(log_file, &archived_log_file);
317    }
318
319    // Set up file appender layer with a non-blocking writer
320    let file_appender = tracing_appender::rolling::never(path, file_name);
321    let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
322    let subscriber = subscriber.with(
323        tracing_subscriber::fmt::Layer::default()
324            .with_writer(non_blocking)
325            .with_ansi(false)
326            .with_filter(tracing_subscriber::filter::FilterFn::new(|meta| {
327                meta.fields().field("tracy.frame_mark").is_none()
328            }))
329    );
330
331    // Register editor log layer
332    #[cfg(feature = "editor")]
333    let subscriber = subscriber.with(editor_layer::EditorLogLayer);
334
335    // Register puffin layer
336    #[cfg(feature = "puffin")]
337    let subscriber = subscriber.with(PuffinLayer::default());
338    #[cfg(feature = "puffin")]
339    {
340        puffin::set_scopes_on(true);
341        app.add_systems(Update, puffin_layer::puffin_new_frame_system);
342    }
343
344    // Register tracy layer
345    #[cfg(feature = "tracing")]
346    let subscriber = subscriber.with(tracing_tracy::TracyLayer::default());
347
348    (subscriber, _guard)
349}