bevy_log/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc(
html_logo_url = "https://bevyengine.org/assets/icon.png",
html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]
//! This crate provides logging functions and configuration for [Bevy](https://bevyengine.org)
//! apps, and automatically configures platform specific log handlers (i.e. Wasm or Android).
//!
//! The macros provided for logging are reexported from [`tracing`](https://docs.rs/tracing),
//! and behave identically to it.
//!
//! By default, the [`LogPlugin`] from this crate is included in Bevy's `DefaultPlugins`
//! and the logging macros can be used out of the box, if used.
//!
//! For more fine-tuned control over logging behavior, set up the [`LogPlugin`] or
//! `DefaultPlugins` during app initialization.
extern crate alloc;
use core::error::Error;
#[cfg(target_os = "android")]
mod android_tracing;
mod once;
#[cfg(feature = "trace_tracy_memory")]
#[global_allocator]
static GLOBAL: tracy_client::ProfiledAllocator<std::alloc::System> =
tracy_client::ProfiledAllocator::new(std::alloc::System, 100);
/// The log prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
#[doc(hidden)]
pub use tracing::{
debug, debug_span, error, error_span, info, info_span, trace, trace_span, warn, warn_span,
};
#[doc(hidden)]
pub use crate::{debug_once, error_once, info_once, trace_once, warn_once};
#[doc(hidden)]
pub use bevy_utils::once;
}
pub use bevy_utils::once;
pub use tracing::{
self, debug, debug_span, error, error_span, info, info_span, trace, trace_span, warn,
warn_span, Level,
};
pub use tracing_subscriber;
use bevy_app::{App, Plugin};
use tracing_log::LogTracer;
use tracing_subscriber::{
filter::{FromEnvError, ParseError},
prelude::*,
registry::Registry,
EnvFilter, Layer,
};
#[cfg(feature = "tracing-chrome")]
use {
bevy_ecs::resource::Resource,
bevy_utils::synccell::SyncCell,
tracing_subscriber::fmt::{format::DefaultFields, FormattedFields},
};
/// Wrapper resource for `tracing-chrome`'s flush guard.
/// When the guard is dropped the chrome log is written to file.
#[cfg(feature = "tracing-chrome")]
#[expect(
dead_code,
reason = "`FlushGuard` never needs to be read, it just needs to be kept alive for the `App`'s lifetime."
)]
#[derive(Resource)]
pub(crate) struct FlushGuard(SyncCell<tracing_chrome::FlushGuard>);
/// Adds logging to Apps. This plugin is part of the `DefaultPlugins`. Adding
/// this plugin will setup a collector appropriate to your target platform:
/// * Using [`tracing-subscriber`](https://crates.io/crates/tracing-subscriber) by default,
/// logging to `stdout`.
/// * Using [`android_log-sys`](https://crates.io/crates/android_log-sys) on Android,
/// logging to Android logs.
/// * Using [`tracing-wasm`](https://crates.io/crates/tracing-wasm) in Wasm, logging
/// to the browser console.
///
/// You can configure this plugin.
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup};
/// # use bevy_log::LogPlugin;
/// # use tracing::Level;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins.set(LogPlugin {
/// level: Level::DEBUG,
/// filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
/// custom_layer: |_| None,
/// }))
/// .run();
/// }
/// ```
///
/// Log level can also be changed using the `RUST_LOG` environment variable.
/// For example, using `RUST_LOG=wgpu=error,bevy_render=info,bevy_ecs=trace cargo run ..`
///
/// It has the same syntax as the field [`LogPlugin::filter`], see [`EnvFilter`].
/// If you define the `RUST_LOG` environment variable, the [`LogPlugin`] settings
/// will be ignored.
///
/// Also, to disable color terminal output (ANSI escape codes), you can
/// set the environment variable `NO_COLOR` to any value. This common
/// convention is documented at [no-color.org](https://no-color.org/).
/// For example:
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup};
/// # use bevy_log::LogPlugin;
/// fn main() {
/// # // SAFETY: Single-threaded
/// # unsafe {
/// std::env::set_var("NO_COLOR", "1");
/// # }
/// App::new()
/// .add_plugins(DefaultPlugins)
/// .run();
/// }
/// ```
///
/// If you want to setup your own tracing collector, you should disable this
/// plugin from `DefaultPlugins`:
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup};
/// # use bevy_log::LogPlugin;
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins.build().disable::<LogPlugin>())
/// .run();
/// }
/// ```
/// # Example Setup
///
/// For a quick setup that enables all first-party logging while not showing any of your dependencies'
/// log data, you can configure the plugin as shown below.
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup};
/// # use bevy_log::*;
/// App::new()
/// .add_plugins(DefaultPlugins.set(LogPlugin {
/// filter: "warn,my_crate=trace".to_string(), //specific filters
/// level: Level::TRACE,//Change this to be globally change levels
/// ..Default::default()
/// }))
/// .run();
/// ```
/// The filter (in this case an `EnvFilter`) chooses whether to print the log. The most specific filters apply with higher priority.
/// Let's start with an example: `filter: "warn".to_string()` will only print logs with level `warn` level or greater.
/// From here, we can change to `filter: "warn,my_crate=trace".to_string()`. Logs will print at level `warn` unless it's in `mycrate`,
/// which will instead print at `trace` level because `my_crate=trace` is more specific.
///
///
/// ## Log levels
/// Events can be logged at various levels of importance.
/// Only events at your configured log level and higher will be shown.
/// ```no_run
/// # use bevy_log::*;
/// // here is how you write new logs at each "log level" (in "most important" to
/// // "least important" order)
/// error!("something failed");
/// warn!("something bad happened that isn't a failure, but that's worth calling out");
/// info!("helpful information that is worth printing by default");
/// debug!("helpful for debugging");
/// trace!("very noisy");
/// ```
/// In addition to `format!` style arguments, you can print a variable's debug
/// value by using syntax like: `trace(?my_value)`.
///
/// ## Per module logging levels
/// Modules can have different logging levels using syntax like `crate_name::module_name=debug`.
///
///
/// ```no_run
/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup};
/// # use bevy_log::*;
/// App::new()
/// .add_plugins(DefaultPlugins.set(LogPlugin {
/// filter: "warn,my_crate=trace,my_crate::my_module=debug".to_string(), // Specific filters
/// level: Level::TRACE, // Change this to be globally change levels
/// ..Default::default()
/// }))
/// .run();
/// ```
/// The idea is that instead of deleting logs when they are no longer immediately applicable,
/// you just disable them. If you do need to log in the future, then you can enable the logs instead of having to rewrite them.
///
/// ## Further reading
///
/// The `tracing` crate has much more functionality than these examples can show.
/// Much of this configuration can be done with "layers" in the `log` crate.
/// Check out:
/// - Using spans to add more fine grained filters to logs
/// - Adding instruments to capture more function information
/// - Creating layers to add additional context such as line numbers
/// # Panics
///
/// This plugin should not be added multiple times in the same process. This plugin
/// sets up global logging configuration for **all** Apps in a given process, and
/// rerunning the same initialization multiple times will lead to a panic.
///
/// # Performance
///
/// Filters applied through this plugin are computed at _runtime_, which will
/// have a non-zero impact on performance.
/// To achieve maximum performance, consider using
/// [_compile time_ filters](https://docs.rs/log/#compile-time-filters)
/// provided by the [`log`](https://crates.io/crates/log) crate.
///
/// ```toml
/// # cargo.toml
/// [dependencies]
/// log = { version = "0.4", features = ["max_level_debug", "release_max_level_warn"] }
/// ```
pub struct LogPlugin {
/// Filters logs using the [`EnvFilter`] format
pub filter: String,
/// Filters out logs that are "less than" the given level.
/// This can be further filtered using the `filter` setting.
pub level: Level,
/// Optionally add an extra [`Layer`] to the tracing subscriber
///
/// This function is only called once, when the plugin is built.
///
/// Because [`BoxedLayer`] takes a `dyn Layer`, `Vec<Layer>` is also an acceptable return value.
///
/// Access to [`App`] is also provided to allow for communication between the
/// [`Subscriber`](tracing::Subscriber) and the [`App`].
///
/// Please see the `examples/log_layers.rs` for a complete example.
pub custom_layer: fn(app: &mut App) -> Option<BoxedLayer>,
}
/// A boxed [`Layer`] that can be used with [`LogPlugin`].
pub type BoxedLayer = Box<dyn Layer<Registry> + Send + Sync + 'static>;
/// The default [`LogPlugin`] [`EnvFilter`].
pub const DEFAULT_FILTER: &str = "wgpu=error,naga=warn";
impl Default for LogPlugin {
fn default() -> Self {
Self {
filter: DEFAULT_FILTER.to_string(),
level: Level::INFO,
custom_layer: |_| None,
}
}
}
impl Plugin for LogPlugin {
#[expect(clippy::print_stderr, reason = "Allowed during logger setup")]
fn build(&self, app: &mut App) {
#[cfg(feature = "trace")]
{
let old_handler = std::panic::take_hook();
std::panic::set_hook(Box::new(move |infos| {
eprintln!("{}", tracing_error::SpanTrace::capture());
old_handler(infos);
}));
}
let finished_subscriber;
let subscriber = Registry::default();
// add optional layer provided by user
let subscriber = subscriber.with((self.custom_layer)(app));
let default_filter = { format!("{},{}", self.level, self.filter) };
let filter_layer = EnvFilter::try_from_default_env()
.or_else(|from_env_error| {
_ = from_env_error
.source()
.and_then(|source| source.downcast_ref::<ParseError>())
.map(|parse_err| {
// we cannot use the `error!` macro here because the logger is not ready yet.
eprintln!("LogPlugin failed to parse filter from env: {}", parse_err);
});
Ok::<EnvFilter, FromEnvError>(EnvFilter::builder().parse_lossy(&default_filter))
})
.unwrap();
let subscriber = subscriber.with(filter_layer);
#[cfg(feature = "trace")]
let subscriber = subscriber.with(tracing_error::ErrorLayer::default());
#[cfg(all(
not(target_arch = "wasm32"),
not(target_os = "android"),
not(target_os = "ios")
))]
{
#[cfg(feature = "tracing-chrome")]
let chrome_layer = {
let mut layer = tracing_chrome::ChromeLayerBuilder::new();
if let Ok(path) = std::env::var("TRACE_CHROME") {
layer = layer.file(path);
}
let (chrome_layer, guard) = layer
.name_fn(Box::new(|event_or_span| match event_or_span {
tracing_chrome::EventOrSpan::Event(event) => event.metadata().name().into(),
tracing_chrome::EventOrSpan::Span(span) => {
if let Some(fields) =
span.extensions().get::<FormattedFields<DefaultFields>>()
{
format!("{}: {}", span.metadata().name(), fields.fields.as_str())
} else {
span.metadata().name().into()
}
}
}))
.build();
app.insert_resource(FlushGuard(SyncCell::new(guard)));
chrome_layer
};
#[cfg(feature = "tracing-tracy")]
let tracy_layer = tracing_tracy::TracyLayer::default();
// note: the implementation of `Default` reads from the env var NO_COLOR
// to decide whether to use ANSI color codes, which is common convention
// https://no-color.org/
let fmt_layer = tracing_subscriber::fmt::Layer::default().with_writer(std::io::stderr);
// bevy_render::renderer logs a `tracy.frame_mark` event every frame
// at Level::INFO. Formatted logs should omit it.
#[cfg(feature = "tracing-tracy")]
let fmt_layer =
fmt_layer.with_filter(tracing_subscriber::filter::FilterFn::new(|meta| {
meta.fields().field("tracy.frame_mark").is_none()
}));
let subscriber = subscriber.with(fmt_layer);
#[cfg(feature = "tracing-chrome")]
let subscriber = subscriber.with(chrome_layer);
#[cfg(feature = "tracing-tracy")]
let subscriber = subscriber.with(tracy_layer);
finished_subscriber = subscriber;
}
#[cfg(target_arch = "wasm32")]
{
finished_subscriber = subscriber.with(tracing_wasm::WASMLayer::new(
tracing_wasm::WASMLayerConfig::default(),
));
}
#[cfg(target_os = "android")]
{
finished_subscriber = subscriber.with(android_tracing::AndroidLayer::default());
}
#[cfg(target_os = "ios")]
{
finished_subscriber = subscriber.with(tracing_oslog::OsLogger::default());
}
let logger_already_set = LogTracer::init().is_err();
let subscriber_already_set =
tracing::subscriber::set_global_default(finished_subscriber).is_err();
match (logger_already_set, subscriber_already_set) {
(true, true) => error!(
"Could not set global logger and tracing subscriber as they are already set. Consider disabling LogPlugin."
),
(true, false) => error!("Could not set global logger as it is already set. Consider disabling LogPlugin."),
(false, true) => error!("Could not set global tracing subscriber as it is already set. Consider disabling LogPlugin."),
(false, false) => (),
}
}
}