use ntime;
use std::env;
use std::path;
use crate::constant::PROCESS_ID;
use crate::format;
use crate::sink::file;
use crate::sink::io::IO;
pub struct LogFileConfig {
pub log_directory: path::PathBuf,
pub formatter_cfg: format::FormatterConfig,
pub local_timestamp: bool,
pub buffered: bool,
pub flush_on_write: bool,
pub append: bool,
}
impl<'i> Default for LogFileConfig {
fn default() -> Self {
Self {
log_directory: env::temp_dir(),
formatter_cfg: format::FormatterConfig::default(),
local_timestamp: false,
buffered: true,
flush_on_write: false,
append: true,
}
}
}
pub fn new<'f>(conf: LogFileConfig) -> IO<'f> {
let current_exe = env::current_exe();
let process_name = match ¤t_exe {
Ok(ce) => ce.file_name().and_then(|n| n.to_str()).unwrap_or("process_invalid_name"),
Err(_) => "process",
};
let log_file_name = path::PathBuf::from(format!(
"{process_name}_{timestamp}_{pid}.log",
timestamp = ntime::Timestamp::now().as_string(if conf.local_timestamp { &ntime::Format::LocalFileName } else { &ntime::Format::UtcFileName }),
pid = *PROCESS_ID,
));
let mut log_path = conf.log_directory;
log_path.push(log_file_name);
file::new(file::FileConfig {
name: format!("log file for {process_name}"),
path: Some(log_path),
formatter_cfg: conf.formatter_cfg,
buffered: conf.buffered,
flush_on_write: conf.flush_on_write,
append: conf.append,
})
}
pub fn default<'f>() -> IO<'f> {
new(LogFileConfig::default())
}
pub fn default_json<'f>() -> IO<'f> {
new(LogFileConfig {
formatter_cfg: format::FormatterConfig {
format: format::OutputFormat::Json,
..format::FormatterConfig::default()
},
..LogFileConfig::default()
})
}