Skip to content

Instantly share code, notes, and snippets.

@thebluefish
Created May 9, 2024 15:36
Show Gist options
  • Save thebluefish/8e132c2a063e37a38843db5b5df0342b to your computer and use it in GitHub Desktop.
Save thebluefish/8e132c2a063e37a38843db5b5df0342b to your computer and use it in GitHub Desktop.
#[allow(unused_imports)]
use tracing::{info,warn,debug,error};
use std::{io, fs};
use std::path::Path;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter };
/// Sets up logging to both stdout and files
pub fn setup<P: AsRef<Path> + Clone>(crate_name: &str, dir: P) -> WorkerGuard {
// Ensures logging dir exists
fs::create_dir_all(dir.clone()).expect("Failed to create tempdir");
// Common formatting options for all outputs
let format = fmt::format()
.compact()
.with_thread_ids(true)
;
// Logging to file
let file_appender = tracing_appender::rolling::daily(dir.as_ref(), dir.as_ref().join(format!("{crate_name}.log")));
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
// Setup the subscriber
let subscriber = tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| format!("info,{crate_name}=info").into()))
.with(fmt::Layer::new().with_writer(io::stdout).event_format(format.clone()))
.with(fmt::Layer::new().with_writer(non_blocking).with_ansi(false).event_format(format))
;
#[cfg(feature = "tracy")]
let subscriber = subscriber.with(tracing_tracy::TracyLayer::default());
tracing::subscriber::set_global_default(subscriber).expect("Unable to set a global subscriber");
guard
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment