diff options
Diffstat (limited to 'src/logging.rs')
| -rw-r--r-- | src/logging.rs | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/logging.rs b/src/logging.rs new file mode 100644 index 0000000..fd81dba --- /dev/null +++ b/src/logging.rs @@ -0,0 +1,54 @@ +use std::{io::Error, path::PathBuf, str::FromStr}; + +use tracing_error::ErrorLayer; +use tracing_subscriber::{self, Layer, layer::SubscriberExt, util::SubscriberInitExt}; + +const LOG_FILE: &'static str = "equity-tracker.log"; + +const LOG_LEVEL: &'static str = "LOG_LEVEL"; +const DEFAULT_LOG_LEVEL: &'static str = "DEBUG"; + +const LOG_DIRECTORY: &'static str = "LOG_DIRECTORY"; +const DEFAULT_LOG_DIRECTORY: &'static str = "./target"; + +/// Either retrieves the environment variable or uses a default value +fn get_env_var(var_name: &'static str, default: &'static str) -> String { + if let Ok(env_var) = std::env::var(var_name) { + env_var + } else { + default.into() + } +} + +/// Provides a PathBuf of the configured log directory, or the target directory +fn get_log_directory() -> std::io::Result<PathBuf> { + let env_dir = get_env_var(LOG_DIRECTORY, DEFAULT_LOG_DIRECTORY); + let path = PathBuf::from_str(&env_dir).map_err(|e| Error::other(e))?; + + Ok(path) +} + +/// Configure the logging through tracing +pub fn initialize_logging() -> std::io::Result<()> { + let directory = get_log_directory()?; + std::fs::create_dir_all(directory.clone())?; + + let log_path = directory.join(LOG_FILE); + let log_file = std::fs::File::create(log_path)?; + + let log_filter = get_env_var(LOG_LEVEL, DEFAULT_LOG_LEVEL); + let file_subscriber = tracing_subscriber::fmt::layer() + .with_file(true) + .with_line_number(true) + .with_target(false) + .with_ansi(false) + .with_writer(log_file) + .with_filter(tracing_subscriber::filter::EnvFilter::builder().parse_lossy(log_filter)); + + tracing_subscriber::registry() + .with(file_subscriber) + .with(ErrorLayer::default()) + .init(); + + Ok(()) +} |
