examples: use tempfile in inferno-flame

This commit updates the `inferno-flame` example to use the `tempfile`
crate as a replacement
for the unmaintained `tempdir` crate.

Also, the previous version of the example output the flamegraph inside
the temporary directory. Since the temporary directory is cleaned up
when the program exits, this means the user can't actually look at the
flamegraph when running this example. I've changed the example to put the
flamegraph in the current working dir instead, so the user can look at
it.

Signed-off-by: Eliza Weisman <eliza@buoyant.io>
This commit is contained in:
Eliza Weisman 2021-08-16 10:55:39 -07:00
parent 058c9e2519
commit 20e1588cfb
2 changed files with 26 additions and 12 deletions

View File

@ -48,7 +48,7 @@ log = "0.4"
# inferno example
inferno = "0.10.0"
tempdir = "0.3.7"
tempfile = "3"
# opentelemetry example
opentelemetry = { version = "0.16", default-features = false, features = ["trace"] }

View File

@ -1,9 +1,11 @@
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;
use std::thread::sleep;
use std::time::Duration;
use tempdir::TempDir;
use std::{
env,
fs::File,
io::{BufReader, BufWriter},
path::{Path, PathBuf},
thread::sleep,
time::Duration,
};
use tracing::{span, Level};
use tracing_flame::FlameLayer;
use tracing_subscriber::{prelude::*, registry::Registry};
@ -20,11 +22,12 @@ fn setup_global_subscriber(dir: &Path) -> impl Drop {
_guard
}
fn make_flamegraph(dir: &Path) {
let inf = File::open(dir.join(PATH)).unwrap();
fn make_flamegraph(tmpdir: &Path, out: &Path) {
println!("outputting flamegraph to {}", out.display());
let inf = File::open(tmpdir.join(PATH)).unwrap();
let reader = BufReader::new(inf);
let out = File::create(dir.join("inferno.svg")).unwrap();
let out = File::create(out).unwrap();
let writer = BufWriter::new(out);
let mut opts = inferno::flamegraph::Options::default();
@ -32,8 +35,19 @@ fn make_flamegraph(dir: &Path) {
}
fn main() {
let out = if let Some(arg) = env::args().nth(1) {
PathBuf::from(arg)
} else {
let mut path = env::current_dir().expect("failed to read current directory");
path.push("tracing-flame-inferno.svg");
path
};
// setup the flame layer
let tmp_dir = TempDir::new("flamegraphs").unwrap();
let tmp_dir = tempfile::Builder::new()
.prefix("flamegraphs")
.tempdir()
.expect("failed to create temporary directory");
let guard = setup_global_subscriber(tmp_dir.path());
// do a bunch of span entering and exiting to simulate a program running
@ -52,5 +66,5 @@ fn main() {
// drop the guard to make sure the layer flushes its output then read the
// output to create the flamegraph
drop(guard);
make_flamegraph(tmp_dir.path());
make_flamegraph(tmp_dir.path(), out.as_ref());
}