1
0
mirror of https://github.com/containers/youki synced 2024-11-23 09:21:57 +01:00

Add debug flag (#465)

This commit is contained in:
unknowndevQwQ 2021-11-18 03:35:59 +08:00 committed by GitHub
parent ef8770df02
commit acf6e31176
Signed by: GitHub
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 8 deletions

@ -1,9 +1,12 @@
//! Default Youki Logger
use anyhow::{bail, Context, Result};
use log::LevelFilter;
use std::borrow::Cow;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::str::FromStr;
/// If in debug mode, default level is debug to get maximum logging
#[cfg(debug_assertions)]
@ -19,7 +22,18 @@ const LOG_FORMAT_JSON: &str = "json";
/// 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>, log_format: Option<String>) -> Result<()> {
pub fn init(
log_debug_flag: bool,
log_file: Option<PathBuf>,
log_format: Option<String>,
) -> Result<()> {
let filter: Cow<str> = if log_debug_flag {
"debug".into()
} else if let Ok(level) = std::env::var("YOUKI_LOG_LEVEL") {
level.into()
} else {
DEFAULT_LOG_LEVEL.into()
};
let formatter = match log_format.as_deref() {
None | Some(LOG_FORMAT_TEXT) => text_write,
Some(LOG_FORMAT_JSON) => json_write,
@ -36,12 +50,11 @@ pub fn init(log_file: Option<PathBuf>, log_format: Option<String>) -> Result<()>
} else {
env_logger::Target::Stderr
};
env_logger::Builder::from_env(
env_logger::Env::default().filter_or("YOUKI_LOG_LEVEL", DEFAULT_LOG_LEVEL),
)
.format(formatter)
.target(target)
.init();
env_logger::Builder::new()
.filter_level(LevelFilter::from_str(filter.as_ref()).context("failed to parse log level")?)
.format(formatter)
.target(target)
.init();
Ok(())
}

@ -38,6 +38,10 @@ use nix::unistd::getuid;
#[derive(Parser, Debug)]
#[clap(version = crate_version!(), author = "youki team")]
struct Opts {
/// change log level to debug.
// Example in future : '--debug change log level to debug. (default: "warn")'
#[clap(long)]
debug: bool,
#[clap(short, long)]
log: Option<PathBuf>,
#[clap(long)]
@ -104,7 +108,7 @@ fn main() -> Result<()> {
let opts = Opts::parse();
if let Err(e) = crate::logger::init(opts.log, opts.log_format) {
if let Err(e) = crate::logger::init(opts.debug, opts.log, opts.log_format) {
eprintln!("log init failed: {:?}", e);
}