1
0
mirror of https://github.com/containers/youki synced 2024-12-03 18:48:22 +01:00

Comment and modify Log module:

Now the default log level is set according to type of compilation debug/production
This commit is contained in:
Yashodhan Joshi 2021-07-15 16:04:34 +05:30
parent 1fb364485e
commit c136125030

@ -12,21 +12,39 @@ use anyhow::Result;
use log::{LevelFilter, Log, Metadata, Record}; use log::{LevelFilter, Log, Metadata, Record};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
/// Public global variables to access logger and logfile
pub static YOUKI_LOGGER: OnceCell<YoukiLogger> = OnceCell::new(); pub static YOUKI_LOGGER: OnceCell<YoukiLogger> = OnceCell::new();
pub static LOG_FILE: OnceCell<Option<File>> = OnceCell::new(); pub static LOG_FILE: OnceCell<Option<File>> = OnceCell::new();
/// If in debug mode, default level is debug to get maximum logging
#[cfg(debug_assertions)]
const DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Debug;
/// If not in debug mode, default level is warn to get important logs
#[cfg(not(debug_assertions))]
const DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Warn;
/// Initialize the logger, must be called before accessing the logger
/// Multiple parts might call this at once, but the actual initialization
/// is done only once due to use of OnceCell
pub fn init(log_file: Option<PathBuf>) -> Result<()> { pub fn init(log_file: Option<PathBuf>) -> Result<()> {
// If file exists, ignore, else create and open the file
let _log_file = LOG_FILE.get_or_init(|| -> Option<File> { let _log_file = LOG_FILE.get_or_init(|| -> Option<File> {
// set the log level if specified in env variable or set to default
let level_filter = if let Ok(log_level_str) = env::var("YOUKI_LOG_LEVEL") { let level_filter = if let Ok(log_level_str) = env::var("YOUKI_LOG_LEVEL") {
LevelFilter::from_str(&log_level_str).unwrap_or(LevelFilter::Warn) LevelFilter::from_str(&log_level_str).unwrap_or(DEFAULT_LOG_LEVEL)
} else { } else {
LevelFilter::Warn DEFAULT_LOG_LEVEL
}; };
// Create a new logger, or get existing if already created
let logger = YOUKI_LOGGER.get_or_init(|| YoukiLogger::new(level_filter.to_level())); let logger = YOUKI_LOGGER.get_or_init(|| YoukiLogger::new(level_filter.to_level()));
log::set_logger(logger) log::set_logger(logger)
.map(|()| log::set_max_level(level_filter)) .map(|()| log::set_max_level(level_filter))
.expect("set logger failed"); .expect("set logger failed");
// Create and open log file
log_file.as_ref().map(|log_file_path| { log_file.as_ref().map(|log_file_path| {
OpenOptions::new() OpenOptions::new()
.create(true) .create(true)
@ -38,17 +56,23 @@ pub fn init(log_file: Option<PathBuf>) -> Result<()> {
}); });
Ok(()) Ok(())
} }
/// Youki's custom Logger
pub struct YoukiLogger { pub struct YoukiLogger {
/// Indicates level up to which logs are to be printed
level: Option<log::Level>, level: Option<log::Level>,
} }
impl YoukiLogger { impl YoukiLogger {
/// Create new logger
pub fn new(level: Option<log::Level>) -> Self { pub fn new(level: Option<log::Level>) -> Self {
Self { level } Self { level }
} }
} }
/// Implements Log interface given by log crate, so we can use its functionality
impl Log for YoukiLogger { impl Log for YoukiLogger {
/// Check if level of given log is enabled or not
fn enabled(&self, metadata: &Metadata) -> bool { fn enabled(&self, metadata: &Metadata) -> bool {
if let Some(level) = self.level { if let Some(level) = self.level {
metadata.level() <= level metadata.level() <= level
@ -57,6 +81,7 @@ impl Log for YoukiLogger {
} }
} }
/// Function to carry out logging
fn log(&self, record: &Record) { fn log(&self, record: &Record) {
if self.enabled(record.metadata()) { if self.enabled(record.metadata()) {
let log_msg = match (record.file(), record.line()) { let log_msg = match (record.file(), record.line()) {
@ -75,6 +100,8 @@ impl Log for YoukiLogger {
record.args() record.args()
), ),
}; };
// if log file is set, write to it, else write to stderr
if let Some(mut log_file) = LOG_FILE.get().unwrap().as_ref() { if let Some(mut log_file) = LOG_FILE.get().unwrap().as_ref() {
let _ = writeln!(log_file, "{}", log_msg); let _ = writeln!(log_file, "{}", log_msg);
} else { } else {
@ -83,6 +110,7 @@ impl Log for YoukiLogger {
} }
} }
/// Flush logs to file
fn flush(&self) { fn flush(&self) {
if let Some(mut log_file) = LOG_FILE.get().unwrap().as_ref() { if let Some(mut log_file) = LOG_FILE.get().unwrap().as_ref() {
log_file.flush().expect("Failed to flush"); log_file.flush().expect("Failed to flush");