docs/bevy/examples/app/logs.rs 2.8 K · 81 lines · raw · history

1 //! This example illustrates how to use logs in bevy.
2
3 use bevy::{log::once, prelude::*};
4
5 fn main() {
6 App::new()
7 .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
8 // Uncomment this to override the default log settings:
9 // level: bevy::log::Level::TRACE,
10 // filter: "wgpu=warn,bevy_ecs=info".to_string(),
11 ..default()
12 }))
13 .add_systems(Startup, setup)
14 .add_systems(Update, log_system)
15 .add_systems(Update, log_once_system)
16 .add_systems(Update, panic_on_p)
17 .run();
18 }
19
20 fn setup(mut commands: Commands) {
21 commands.spawn(Camera2d);
22 commands.spawn((
23 Text::new("Press P to panic"),
24 Node {
25 position_type: PositionType::Absolute,
26 top: px(12),
27 left: px(12),
28 ..default()
29 },
30 ));
31 }
32
33 fn panic_on_p(keys: Res<ButtonInput<KeyCode>>) {
34 if keys.just_pressed(KeyCode::KeyP) {
35 panic!("P pressed, panicking");
36 }
37 }
38
39 fn log_system() {
40 // here is how you write new logs at each "log level" (in "least important" to "most important"
41 // order)
42 trace!("very noisy");
43 debug!("helpful for debugging");
44 info!("helpful information that is worth printing by default");
45 warn!("something bad happened that isn't a failure, but thats worth calling out");
46 error!("something failed");
47
48 // by default, trace and debug logs are ignored because they are "noisy"
49 // you can control what level is logged by setting up the LogPlugin
50 // alternatively you can set the log level via the RUST_LOG=LEVEL environment variable
51 // ex: RUST_LOG=trace, RUST_LOG=info,bevy_ecs=warn
52 // the format used here is super flexible. check out this documentation for more info:
53 // https://docs.rs/tracing-subscriber/*/tracing_subscriber/filter/struct.EnvFilter.html
54 }
55
56 fn log_once_system() {
57 // The 'once' variants of each log level are useful when a system is called every frame,
58 // but we still wish to inform the user only once. In other words, use these to prevent spam :)
59
60 trace_once!("one time noisy message");
61 debug_once!("one time debug message");
62 info_once!("some info which is printed only once");
63 warn_once!("some warning we wish to call out only once");
64 error_once!("some error we wish to report only once");
65
66 for i in 0..10 {
67 info_once!("logs once per call site, so this works just fine: {}", i);
68 }
69
70 // you can also use the `once!` macro directly,
71 // in situations where you want to do something expensive only once
72 // within the context of a continuous system.
73 once!({
74 info!("doing expensive things");
75 let mut a: u64 = 0;
76 for i in 0..100000000 {
77 a += i;
78 }
79 info!("result of some expensive one time calculation: {}", a);
80 });
81 }