๐Ÿ“ฆ bevyengine / bevy

๐Ÿ“„ log_layers.rs ยท 77 lines
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//! This example illustrates how to add custom log layers in bevy.

use bevy::{
    log::{
        tracing::{self, Subscriber},
        tracing_subscriber::{field::MakeExt, Layer},
        BoxedFmtLayer, BoxedLayer,
    },
    prelude::*,
};

struct CustomLayer;

impl<S: Subscriber> Layer<S> for CustomLayer {
    fn on_event(
        &self,
        event: &tracing::Event<'_>,
        _ctx: bevy::log::tracing_subscriber::layer::Context<'_, S>,
    ) {
        println!("Got event!");
        println!("  level={}", event.metadata().level());
        println!("  target={}", event.metadata().target());
        println!("  name={}", event.metadata().name());
    }
}

// We don't need App for this example, as we are just printing log information.
// For an example that uses App, see log_layers_ecs.
fn custom_layer(_app: &mut App) -> Option<BoxedLayer> {
    // You can provide multiple layers like this, since Vec<Layer> is also a layer:
    Some(Box::new(vec![
        bevy::log::tracing_subscriber::fmt::layer()
            .with_file(true)
            .boxed(),
        CustomLayer.boxed(),
    ]))
}

// While `custom_layer` allows you to add _additional_ layers, it won't allow you to override the
// default `tracing_subscriber::fmt::Layer` added by `LogPlugin`. To do that, you can use the
// `fmt_layer` option.
//
// In this example, we're disabling the timestamp in the log output and enabling the alternative debugging format.
// This formatting inserts newlines into logs that use the debug sigil (`?`) like `info!(foo=?bar)`
fn fmt_layer(_app: &mut App) -> Option<BoxedFmtLayer> {
    Some(Box::new(
        bevy::log::tracing_subscriber::fmt::Layer::default()
            .without_time()
            .map_fmt_fields(MakeExt::debug_alt)
            .with_writer(std::io::stderr),
    ))
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
            custom_layer,
            fmt_layer,

            ..default()
        }))
        .add_systems(Update, log_system)
        .run();
}

fn log_system() {
    // 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 thats worth calling out");
    info!("helpful information that is worth printing by default");
    let secret_message = "Bevy";
    info!(?secret_message, "Here's a log that uses the debug sigil");
    debug!("helpful for debugging");
    trace!("very noisy");
}