Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/app/log_layers_ecs.rs
6592 views
1
//! This example illustrates how to transfer log events from the [`Layer`] to Bevy's ECS.
2
//!
3
//! The way we will do this is via a [`mpsc`] channel. [`mpsc`] channels allow 2 unrelated
4
//! parts of the program to communicate (in this case, [`Layer`]s and Bevy's ECS).
5
//!
6
//! Inside the `custom_layer` function we will create a [`mpsc::Sender`] and a [`mpsc::Receiver`] from a
7
//! [`mpsc::channel`]. The [`Sender`](mpsc::Sender) will go into the `AdvancedLayer` and the [`Receiver`](mpsc::Receiver) will
8
//! go into a non-send resource called `LogEvents` (It has to be non-send because [`Receiver`](mpsc::Receiver) is [`!Sync`](Sync)).
9
//! From there we will use `transfer_log_events` to transfer log events from `LogEvents` to an ECS event called `LogEvent`.
10
//!
11
//! Finally, after all that we can access the `LogEvent` event from our systems and use it.
12
//! In this example we build a simple log viewer.
13
14
use std::sync::mpsc;
15
16
use bevy::{
17
log::{
18
tracing::{self, Subscriber},
19
tracing_subscriber::{self, Layer},
20
BoxedLayer, Level,
21
},
22
prelude::*,
23
};
24
25
fn main() {
26
App::new()
27
.add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
28
// Show logs all the way up to the trace level, but only for logs
29
// produced by this example.
30
level: Level::TRACE,
31
filter: "warn,log_layers_ecs=trace".to_string(),
32
custom_layer,
33
..default()
34
}))
35
.add_systems(Startup, (log_system, setup))
36
.add_systems(Update, print_logs)
37
.run();
38
}
39
40
/// A basic message. This is what we will be sending from the [`CaptureLayer`] to [`CapturedLogEvents`] non-send resource.
41
#[derive(Debug, BufferedEvent)]
42
struct LogEvent {
43
message: String,
44
level: Level,
45
}
46
47
/// This non-send resource temporarily stores [`LogEvent`]s before they are
48
/// written to [`Events<LogEvent>`] by [`transfer_log_events`].
49
#[derive(Deref, DerefMut)]
50
struct CapturedLogEvents(mpsc::Receiver<LogEvent>);
51
52
/// Transfers information from the `LogEvents` resource to [`Events<LogEvent>`](LogEvent).
53
fn transfer_log_events(
54
receiver: NonSend<CapturedLogEvents>,
55
mut log_events: EventWriter<LogEvent>,
56
) {
57
// Make sure to use `try_iter()` and not `iter()` to prevent blocking.
58
log_events.write_batch(receiver.try_iter());
59
}
60
61
/// This is the [`Layer`] that we will use to capture log events and then send them to Bevy's
62
/// ECS via its [`mpsc::Sender`].
63
struct CaptureLayer {
64
sender: mpsc::Sender<LogEvent>,
65
}
66
67
impl<S: Subscriber> Layer<S> for CaptureLayer {
68
fn on_event(
69
&self,
70
event: &tracing::Event<'_>,
71
_ctx: tracing_subscriber::layer::Context<'_, S>,
72
) {
73
// In order to obtain the log message, we have to create a struct that implements
74
// Visit and holds a reference to our string. Then we use the `record` method and
75
// the struct to modify the reference to hold the message string.
76
let mut message = None;
77
event.record(&mut CaptureLayerVisitor(&mut message));
78
if let Some(message) = message {
79
let metadata = event.metadata();
80
81
self.sender
82
.send(LogEvent {
83
message,
84
level: *metadata.level(),
85
})
86
.expect("LogEvents resource no longer exists!");
87
}
88
}
89
}
90
91
/// A [`Visit`](tracing::field::Visit)or that records log messages that are transferred to [`CaptureLayer`].
92
struct CaptureLayerVisitor<'a>(&'a mut Option<String>);
93
impl tracing::field::Visit for CaptureLayerVisitor<'_> {
94
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
95
// This if statement filters out unneeded events sometimes show up
96
if field.name() == "message" {
97
*self.0 = Some(format!("{value:?}"));
98
}
99
}
100
}
101
fn custom_layer(app: &mut App) -> Option<BoxedLayer> {
102
let (sender, receiver) = mpsc::channel();
103
104
let layer = CaptureLayer { sender };
105
let resource = CapturedLogEvents(receiver);
106
107
app.insert_non_send_resource(resource);
108
app.add_event::<LogEvent>();
109
app.add_systems(Update, transfer_log_events);
110
111
Some(layer.boxed())
112
}
113
114
fn log_system() {
115
// Here is how you write new logs at each "log level" (in "most important" to
116
// "least important" order)
117
error!("Something failed");
118
warn!("Something bad happened that isn't a failure, but thats worth calling out");
119
info!("Helpful information that is worth printing by default");
120
debug!("Helpful for debugging");
121
trace!("Very noisy");
122
}
123
124
#[derive(Component)]
125
struct LogViewerRoot;
126
127
fn setup(mut commands: Commands) {
128
commands.spawn(Camera2d);
129
130
commands.spawn((
131
Node {
132
width: vw(100),
133
height: vh(100),
134
flex_direction: FlexDirection::Column,
135
padding: UiRect::all(px(12)),
136
..default()
137
},
138
LogViewerRoot,
139
));
140
}
141
142
// This is how we can read our LogEvents.
143
// In this example we are reading the LogEvents and inserting them as text into our log viewer.
144
fn print_logs(
145
mut events: EventReader<LogEvent>,
146
mut commands: Commands,
147
log_viewer_root: Single<Entity, With<LogViewerRoot>>,
148
) {
149
let root_entity = *log_viewer_root;
150
151
commands.entity(root_entity).with_children(|child| {
152
for event in events.read() {
153
child.spawn((
154
Text::default(),
155
children![
156
(
157
TextSpan::new(format!("{:5} ", event.level)),
158
TextColor(level_color(&event.level)),
159
),
160
TextSpan::new(&event.message),
161
],
162
));
163
}
164
});
165
}
166
167
fn level_color(level: &Level) -> Color {
168
use bevy::color::palettes::tailwind::*;
169
Color::from(match *level {
170
Level::WARN => ORANGE_400,
171
Level::ERROR => RED_400,
172
Level::INFO => GREEN_400,
173
Level::TRACE => PURPLE_400,
174
Level::DEBUG => BLUE_400,
175
})
176
}
177
178