Skip to content

Commit ea91df3

Browse files
authored
examples: backport fmt-multiple-writers.rs to v0.1.0 branch (#1187)
It turns out that this example never existed on v0.1.x, which is my bad. Resolves #1179.
1 parent 035342b commit ea91df3

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

examples/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ tracing-log = { path = "../tracing-log", version = "0.1.1", features = ["env_log
2222
tracing-serde = { path = "../tracing-serde" }
2323
tracing-opentelemetry = { path = "../tracing-opentelemetry" }
2424
tracing-journald = { path = "../tracing-journald" }
25+
tracing-appender = { path = "../tracing-appender", version = "0.1.2" }
2526

2627
# serde example
2728
serde_json = "1.0"

examples/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ This directory contains a collection of examples that demonstrate the use of the
2424
fields on spans and events.
2525
+ `fmt-custom-event`: Demonstrates overriding how the `fmt` subscriber formats
2626
events.
27+
+ `fmt-multiple-writers.rs`: demonstrates how `fmt::Layer` can write
28+
to multiple destinations (in this instance, stdout and a file) simultaneously.
2729
+ `subscriber-filter`: Demonstrates the `tracing-subscriber::filter` module,
2830
which provides a layer which adds configurable filtering to a subscriber
2931
implementation.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//! An example demonstrating how `fmt::Layer` can write to multiple
2+
//! destinations (in this instance, `stdout` and a file) simultaneously.
3+
4+
#[path = "fmt/yak_shave.rs"]
5+
mod yak_shave;
6+
7+
use std::io;
8+
use tempdir::TempDir;
9+
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter};
10+
11+
fn main() {
12+
let dir = TempDir::new("directory").expect("Failed to create tempdir");
13+
14+
let file_appender = tracing_appender::rolling::hourly(dir, "example.log");
15+
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
16+
17+
let subscriber = tracing_subscriber::registry()
18+
.with(EnvFilter::from_default_env().add_directive(tracing::Level::TRACE.into()))
19+
.with(fmt::Layer::new().with_writer(io::stdout))
20+
.with(fmt::Layer::new().with_writer(non_blocking));
21+
tracing::subscriber::set_global_default(subscriber).expect("Unable to set a global collector");
22+
23+
let number_of_yaks = 3;
24+
// this creates a new event, outside of any spans.
25+
tracing::info!(number_of_yaks, "preparing to shave yaks");
26+
27+
let number_shaved = yak_shave::shave_all(number_of_yaks);
28+
tracing::info!(
29+
all_yaks_shaved = number_shaved == number_of_yaks,
30+
"yak shaving completed."
31+
);
32+
}

0 commit comments

Comments
 (0)