Last active
February 24, 2024 00:26
-
-
Save thebluefish/509d7cd4b52d18cf66357d87f89751c6 to your computer and use it in GitHub Desktop.
Example for setting up a minimal logger to both file and stdout 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
[features] | |
default = ["tracy"] | |
tracy = [] | |
[dependencies] | |
tracing = "0.1" | |
tracing-appender = "0.2" | |
tracing-subscriber = { version = "0.3", features = ["env-filter"] } | |
tracing-tracy = "0.11.0" |
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
#[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!("warn,{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 | |
} |
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
fn main() -> anyhow::Result<()> { | |
let _guard = logging::setup("foo", "./logs"); | |
// do work | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment