Skip to content

Instantly share code, notes, and snippets.

@alphastrata
Created October 8, 2023 04:38
Show Gist options
  • Select an option

  • Save alphastrata/2e1818a0071286bcb447623e1fc475d2 to your computer and use it in GitHub Desktop.

Select an option

Save alphastrata/2e1818a0071286bcb447623e1fc475d2 to your computer and use it in GitHub Desktop.
termite -- my go to log-to-file boilerplate
pub mod termite {
use std::env;
/// Termite is a simple logging implementation, powered by the fern crate.
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
/// Initialise termite.log, after initilisation you'll find it works EXACTLY as most of the logging
/// crates you're used to.
//
/// #Examples:
/// // it works exactly like the std library's log crate.
/// use fern;
/// use log::{debug, error, info, trace, warn};
///
/// info!("Info you'd like to log");
/// warn!("Warning you'd like to log");
/// error!("Error you'd like to log");
/// trace!("Thing you'd like to trace");
pub fn setup_logger() -> Result<(), fern::InitError> {
match env::var("RUST_LOG") {
Ok(_) => {
std::env::set_var("RUST_LOG", "trace");
warn!("$RUST_LOG was not set in $ENV");
info!("$RUST_LOG set to 'trace'")
}
Err(e) => {
error!("Unable to get, or set $RUST_LOG\n{e}");
}
};
let termite_path = format!("termite_{}.log", chrono::Local::now().format("%Y-%m-%d"));
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{}[{}][{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.level(), // info!() or error!() etc.
record.target(), // The file that spawned this entry into the log.
record.line().unwrap_or(0), // The line number in said file.
message
))
})
.chain(std::io::stdout())
.chain(fern::log_file(termite_path)?)
.apply()?;
trace!("Logger setup complete.");
Ok(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment