Last active
February 23, 2025 20:12
-
-
Save airstrike/465ba5577815f04cd7c614acd6c7a35e to your computer and use it in GitHub Desktop.
Sample simple logging with tracing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::{fs::File, sync::Arc}; | |
| use tracing::Level; | |
| use tracing_subscriber::{ | |
| filter::{LevelFilter, Targets}, | |
| fmt, | |
| prelude::*, | |
| }; | |
| pub use tracing::{debug, error, info, trace, warn}; | |
| // From the excellent example in: | |
| // https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/targets/struct.Targets.html | |
| pub(super) fn init() -> Result<(), std::io::Error> { | |
| // A layer that logs events to stdout using the human-readable "pretty" | |
| // format. | |
| let stdout_log = fmt::layer().compact(); | |
| // A layer that logs events to a file, using the JSON format. | |
| let file = File::create("debug_log.json")?; | |
| let debug_log = fmt::layer().with_writer(Arc::new(file)).json(); | |
| tracing_subscriber::registry() | |
| // Only log INFO and above to stdout, unless the span or event | |
| // has the `my_crate::cool_module` target prefix. | |
| .with( | |
| stdout_log.with_filter( | |
| Targets::default() | |
| .with_target("model", Level::DEBUG) | |
| .with_target("myapp::layout", Level::DEBUG) | |
| .with_target("myapp::widget", Level::DEBUG) | |
| .with_target("myapp::screen", Level::DEBUG) | |
| .with_default(Level::INFO), | |
| ), | |
| ) | |
| // Log everything enabled by the global filter to `debug_log.json`. | |
| .with(debug_log) | |
| // Configure a global filter for the whole subscriber stack. This will | |
| // control what spans and events are recorded by both the `debug_log` | |
| // and the `stdout_log` layers, and `stdout_log` will *additionally* be | |
| // filtered by its per-layer filter. | |
| .with( | |
| Targets::default() | |
| .with_target("myapp", Level::TRACE) | |
| .with_target("iced", Level::WARN) | |
| .with_target("iced_wgpu", Level::WARN) | |
| .with_target("wgpu_core", LevelFilter::OFF), | |
| ) | |
| .init(); | |
| Ok(()) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An even better approach is to just put it in a
logsubcrate withlib.rs:and then you can
log::error!(foo);anywhere from your code