Skip to content

Commit

Permalink
feat(log): add tracing, verbosity, json output
Browse files Browse the repository at this point in the history
  • Loading branch information
QaidVoid committed Nov 9, 2024
1 parent ff004ae commit 424b0e3
Show file tree
Hide file tree
Showing 19 changed files with 423 additions and 199 deletions.
98 changes: 98 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,7 @@ serde_json = "1.0.128"
strip-ansi-escapes = "0.2.0"
termion = "4.0.3"
tokio = { version = "1.40.0", features = ["macros", "rt-multi-thread"] }
tracing = { version = "0.1.40", default-features = false }
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "fmt"], default-features = false }
which = "6.0.3"
xattr = { version = "1.3.1", default-features = false }
11 changes: 8 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use clap::{Parser, Subcommand};
use clap::{ArgAction, Parser, Subcommand};

#[derive(Parser)]
#[command(
Expand All @@ -13,9 +13,14 @@ use clap::{Parser, Subcommand};
arg_required_else_help = true
)]
pub struct Args {
/// Unimplemented
#[arg(short = 'v', long, action = ArgAction::Count)]
pub verbose: u8,

#[arg(short, long)]
pub quiet: bool,

#[arg(short, long)]
pub verbose: bool,
pub json: bool,

#[clap(subcommand)]
pub command: Commands,
Expand Down
26 changes: 11 additions & 15 deletions src/core/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ use std::{cmp::Ordering, future::Future, os::unix::fs::PermissionsExt, path::Pat
use futures::future::join_all;
use libc::{fork, unshare, waitpid, CLONE_NEWUSER, PR_CAPBSET_READ};
use tokio::fs;
use tracing::{info, warn};

use crate::{
core::{
color::{Color, ColorExt},
constant::CAP_MKNOD,
},
successln, warnln,
use crate::core::{
color::{Color, ColorExt},
constant::CAP_MKNOD,
};

use super::constant::CAP_SYS_ADMIN;
Expand Down Expand Up @@ -49,7 +47,7 @@ pub async fn check_health() {
Box::pin(check_capabilities()),
];

println!("{0} FUSE CHECK {0}", "☵".repeat(4));
info!("{0} FUSE CHECK {0}", "☵".repeat(4));
check_fusermount().await;

let results = join_all(checks).await;
Expand All @@ -60,17 +58,15 @@ pub async fn check_health() {
}
});

println!();

println!("{0} USER NAMESPACE CHECK {0}", "☵".repeat(4));
info!("\n{0} USER NAMESPACE CHECK {0}", "☵".repeat(4));
for error in &errors {
warnln!("{}", error);
warn!("{}", error);
}

if errors.is_empty() {
successln!("User namespace checked successfully.")
info!("User namespace checked successfully.")
} else {
println!(
info!(
"{} {}",
"More info at:".color(Color::Cyan),
"https://l.ajam.dev/namespace".color(Color::Blue)
Expand Down Expand Up @@ -168,13 +164,13 @@ async fn check_fusermount() {
}

if !error.is_empty() {
warnln!(
warn!(
"{}\n{} {}",
error,
"More info at:".color(Color::Cyan),
"https://l.ajam.dev/fuse".color(Color::Blue)
);
} else {
successln!("Fuse checked successfully.");
info!("Fuse checked successfully.");
}
}
132 changes: 89 additions & 43 deletions src/core/log.rs
Original file line number Diff line number Diff line change
@@ -1,55 +1,101 @@
#[macro_export]
macro_rules! warnln {
($($arg:tt)*) => {
println!("{} {}", "[WARN]".color(Color::BrightYellow).bold(), format!($($arg)*))
};
}
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::{
fmt::{
self,
format::{FmtSpan, Writer},
FmtContext, FormatEvent, FormatFields,
},
registry::LookupSpan,
};

#[macro_export]
macro_rules! infoln {
($($arg:tt)*) => {
println!("{} {}", "[INFO]".color(Color::BrightBlue).bold(), format!($($arg)*))
};
}
use crate::cli::Args;

#[macro_export]
macro_rules! errorln {
($($arg:tt)*) => {
eprintln!("{} {}", "[ERROR]".color(Color::BrightRed).bold(), format!($($arg)*))
};
}
use super::color::{Color, ColorExt};

#[macro_export]
macro_rules! successln {
($($arg:tt)*) => {
println!("{} {}", "[SUCCESS]".color(Color::BrightGreen).bold(), format!($($arg)*))
};
}
pub struct CustomFormatter;

#[macro_export]
macro_rules! warn {
($($arg:tt)*) => {
print!("{} {}", "[WARN]".color(Color::BrightYellow).bold(), format!($($arg)*))
};
impl<S, N> FormatEvent<S, N> for CustomFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: Writer<'_>,
event: &Event<'_>,
) -> std::fmt::Result {
match *event.metadata().level() {
Level::TRACE => write!(writer, "{} ", "[TRACE]".color(Color::BrightMagenta)),
Level::DEBUG => write!(writer, "{} ", "[DEBUG]".color(Color::BrightBlue)),
Level::INFO => write!(writer, ""),
Level::WARN => write!(writer, "{} ", "[WARN]".color(Color::BrightYellow)),
Level::ERROR => write!(writer, "{} ", "[ERROR]".color(Color::BrightRed)),
}?;

ctx.field_format().format_fields(writer.by_ref(), event)?;

writeln!(writer)
}
}

#[macro_export]
macro_rules! info {
($($arg:tt)*) => {
print!("{} {}", "[INFO]".color(Color::BrightBlue).bold(), format!($($arg)*))
};
pub struct CleanJsonFormatter;

impl<S, N> FormatEvent<S, N> for CleanJsonFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: Writer<'_>,
event: &Event<'_>,
) -> std::fmt::Result {
let mut fields_output = String::new();

let temp_writer = Writer::new(&mut fields_output);
ctx.field_format().format_fields(temp_writer, event)?;
let clean_fields = strip_ansi_escapes::strip_str(&fields_output);

let json = serde_json::json!({
"level": event.metadata().level().to_string(),
"fields": clean_fields,
"target": event.metadata().target(),
});

writeln!(writer, "{}", json)
}
}

#[macro_export]
macro_rules! error {
($($arg:tt)*) => {
eprint!("{} {}", "[ERROR]".color(Color::BrightRed).bold(), format!($($arg)*))
pub fn setup_logging(args: &Args) {
let filter_level = if args.quiet {
Level::ERROR
} else if args.verbose >= 2 {
Level::TRACE
} else if args.verbose == 1 {
Level::DEBUG
} else {
Level::INFO
};
}

#[macro_export]
macro_rules! success {
($($arg:tt)*) => {
print!("{} {}", "[SUCCESS]".color(Color::BrightGreen).bold(), format!($($arg)*))
let builder = fmt::Subscriber::builder()
.with_env_filter(format!("soar_cli={}", filter_level))
.with_target(false)
.with_thread_ids(false)
.with_thread_names(false)
.with_file(false)
.with_line_number(false)
.with_span_events(FmtSpan::NONE)
.with_writer(std::io::stderr)
.compact()
.without_time();

let subscriber: Box<dyn Subscriber + Send + Sync> = if args.json {
Box::new(builder.event_format(CleanJsonFormatter).finish())
} else {
Box::new(builder.event_format(CustomFormatter).finish())
};

tracing::subscriber::set_global_default(subscriber).expect("Failed to set tracing subscriber");
}
Loading

0 comments on commit 424b0e3

Please sign in to comment.