rasant 1.0.0

Rasant is a lightweight, high performance and flexible Rust library for structured logging.
Documentation
//! Log file [sink][`crate::sink`] module.
//!
//! Log file sinks are very similar to regular [crate::sink::file] sinks, but impose an
//! opinionated file name format. Only logging directories are configurable.
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;

/// Configuration struct for an [`IO`] log file [sink][`crate::sink`].
pub struct LogFileConfig {
	/// Base directory for log files, as a [`std::path::PathBuf`]
	pub log_directory: path::PathBuf,
	/// Output formatting configuration.
	pub formatter_cfg: format::FormatterConfig,
	/// Whether to use local or UTC timestamp on log file names.
	pub local_timestamp: bool,
	/// String delimiter, inserted between log writes.
	pub buffered: bool,
	/// Whether to flush immediately after every write operation.
	pub flush_on_write: bool,
	/// Wheter to append on existing file paths, or truncate them.
	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,
		}
	}
}

/// Initializes a [`IO`] log file [sink][`crate::sink`] from a [`LogFileConfig`].
pub fn new<'f>(conf: LogFileConfig) -> IO<'f> {
	let current_exe = env::current_exe();
	let process_name = match &current_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,
	})
}

/// Returns an initialized log file [sink][`crate::sink`] for text, with default values.
pub fn default<'f>() -> IO<'f> {
	new(LogFileConfig::default())
}

/// Returns an initialized log file [sink][`crate::sink`] for JSON, with default values.
pub fn default_json<'f>() -> IO<'f> {
	new(LogFileConfig {
		formatter_cfg: format::FormatterConfig {
			format: format::OutputFormat::Json,
			..format::FormatterConfig::default()
		},
		..LogFileConfig::default()
	})
}