log_layers/
log_layers.rs

1//! This example illustrates how to add custom log layers in bevy.
2
3use bevy::{
4    log::{tracing_subscriber::Layer, BoxedLayer},
5    prelude::*,
6    utils::tracing::Subscriber,
7};
8
9struct CustomLayer;
10
11impl<S: Subscriber> Layer<S> for CustomLayer {
12    fn on_event(
13        &self,
14        event: &bevy::utils::tracing::Event<'_>,
15        _ctx: bevy::log::tracing_subscriber::layer::Context<'_, S>,
16    ) {
17        println!("Got event!");
18        println!("  level={:?}", event.metadata().level());
19        println!("  target={:?}", event.metadata().target());
20        println!("  name={:?}", event.metadata().name());
21    }
22}
23
24// We don't need App for this example, as we are just printing log information.
25// For an example that uses App, see log_layers_ecs.
26fn custom_layer(_app: &mut App) -> Option<BoxedLayer> {
27    // You can provide multiple layers like this, since Vec<Layer> is also a layer:
28    Some(Box::new(vec![
29        bevy::log::tracing_subscriber::fmt::layer()
30            .with_file(true)
31            .boxed(),
32        CustomLayer.boxed(),
33    ]))
34}
35
36fn main() {
37    App::new()
38        .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
39            custom_layer,
40
41            ..default()
42        }))
43        .add_systems(Update, log_system)
44        .run();
45}
46
47fn log_system() {
48    // here is how you write new logs at each "log level" (in "most important" to
49    // "least important" order)
50    error!("something failed");
51    warn!("something bad happened that isn't a failure, but thats worth calling out");
52    info!("helpful information that is worth printing by default");
53    debug!("helpful for debugging");
54    trace!("very noisy");
55}