blob: fd81dba63757e3793ec700a555d8f158988f3578 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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(())
}
|