docs/bevy/examples/app/log_layers.rs 2.5 K · 76 lines · raw · history

1 //! This example illustrates how to add custom log layers in bevy.
2
3 use bevy::{
4 log::{
5 tracing::{self, Subscriber},
6 tracing_subscriber::{field::MakeExt, Layer},
7 BoxedFmtLayer, BoxedLayer,
8 },
9 prelude::*,
10 };
11
12 struct CustomLayer;
13
14 impl<S: Subscriber> Layer<S> for CustomLayer {
15 fn on_event(
16 &self,
17 event: &tracing::Event<'_>,
18 _ctx: bevy::log::tracing_subscriber::layer::Context<'_, S>,
19 ) {
20 println!("Got event!");
21 println!(" level={}", event.metadata().level());
22 println!(" target={}", event.metadata().target());
23 println!(" name={}", event.metadata().name());
24 }
25 }
26
27 // We don't need App for this example, as we are just printing log information.
28 // For an example that uses App, see log_layers_ecs.
29 fn custom_layer(_app: &mut App) -> Option<BoxedLayer> {
30 // You can provide multiple layers like this, since Vec<Layer> is also a layer:
31 Some(Box::new(vec![
32 bevy::log::tracing_subscriber::fmt::layer()
33 .with_file(true)
34 .boxed(),
35 CustomLayer.boxed(),
36 ]))
37 }
38
39 // While `custom_layer` allows you to add _additional_ layers, it won't allow you to override the
40 // default `tracing_subscriber::fmt::Layer` added by `LogPlugin`. To do that, you can use the
41 // `fmt_layer` option.
42 //
43 // In this example, we're disabling the timestamp in the log output and enabling the alternative debugging format.
44 // This formatting inserts newlines into logs that use the debug sigil (`?`) like `info!(foo=?bar)`
45 fn fmt_layer(_app: &mut App) -> Option<BoxedFmtLayer> {
46 Some(Box::new(
47 bevy::log::tracing_subscriber::fmt::Layer::default()
48 .without_time()
49 .map_fmt_fields(MakeExt::debug_alt)
50 .with_writer(std::io::stderr),
51 ))
52 }
53
54 fn main() {
55 App::new()
56 .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
57 custom_layer,
58 fmt_layer,
59
60 ..default()
61 }))
62 .add_systems(Update, log_system)
63 .run();
64 }
65
66 fn log_system() {
67 // here is how you write new logs at each "log level" (in "most important" to
68 // "least important" order)
69 error!("something failed");
70 warn!("something bad happened that isn't a failure, but thats worth calling out");
71 info!("helpful information that is worth printing by default");
72 let secret_message = "Bevy";
73 info!(?secret_message, "Here's a log that uses the debug sigil");
74 debug!("helpful for debugging");
75 trace!("very noisy");
76 }