aboutsummaryrefslogtreecommitdiff
path: root/src/logging.rs
diff options
context:
space:
mode:
authorKevin Hoerr <kjhoerr@submelon.dev>2026-04-22 14:52:59 -0400
committerKevin Hoerr <kjhoerr@submelon.dev>2026-04-22 14:52:59 -0400
commit0952686526e118339b945ccfb84db1dcc69ee2ab (patch)
tree983cc5018ba31f88d89c241c951a38a4cae752c8 /src/logging.rs
parent25246c26c11f485272689b8c7bd7910f90cc38ed (diff)
downloadequity-tracker-0952686526e118339b945ccfb84db1dcc69ee2ab.tar.gz
equity-tracker-0952686526e118339b945ccfb84db1dcc69ee2ab.tar.bz2
equity-tracker-0952686526e118339b945ccfb84db1dcc69ee2ab.zip
Add logging
Diffstat (limited to 'src/logging.rs')
-rw-r--r--src/logging.rs54
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(())
+}