bevy/examples/app/log_layers.rs
Doonv 14c20a6c9c
Add access to App within LogPlugin::update_subscriber (#12045)
# Objective

In my library,
[`bevy_dev_console`](https://github.com/doonv/bevy_dev_console) I need
access to `App` within `LogPlugin::update_subscriber` in order to
communicate with the `App` from my custom `Layer`.

## Solution

Give access to `App`.

---

## Changelog

- Added access to `App` within `LogPlugin::update_subscriber`

## Migration Guide

`LogPlugin::update_subscriber` now has a `&mut App` parameter. If you
don't need access to `App`, you can ignore the parameter with an
underscore (`_`).

```diff,rust
- fn update_subscriber(subscriber: BoxedSubscriber) -> BoxedSubscriber {
+ fn update_subscriber(_: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
      Box::new(subscriber.with(CustomLayer))
  }
```
2024-03-04 00:01:05 +00:00

57 lines
1.9 KiB
Rust

//! This example illustrates how to add custom log layers in bevy.
use bevy::{
log::tracing_subscriber::{layer::SubscriberExt, Layer},
log::BoxedSubscriber,
prelude::*,
utils::tracing::Subscriber,
};
struct CustomLayer;
impl<S: Subscriber> Layer<S> for CustomLayer {
fn on_event(
&self,
event: &bevy::utils::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 update_subscriber(_: &mut App, subscriber: BoxedSubscriber) -> BoxedSubscriber {
Box::new(subscriber.with(CustomLayer))
}
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(bevy::log::LogPlugin {
update_subscriber: Some(update_subscriber),
// You can chain multiple subscriber updates like this:
//
// update_subscriber: Some(|app, subscriber| {
// let subscriber = update_subscriber_a(app, subscriber);
// let subscriber = update_subscriber_b(app, subscriber);
//
// update_subscriber_c(app, subscriber)
// }),
..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");
debug!("helpful for debugging");
trace!("very noisy");
}