From 5de559999d9caa59a6d35e240adc7b43d4db68ea Mon Sep 17 00:00:00 2001 From: rishflab Date: Mon, 13 Dec 2021 18:09:53 +1100 Subject: [PATCH] Enable json logs for the cli --- swap/src/cli/tracing.rs | 81 +++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 23 deletions(-) diff --git a/swap/src/cli/tracing.rs b/swap/src/cli/tracing.rs index daa23f377..5ed582310 100644 --- a/swap/src/cli/tracing.rs +++ b/swap/src/cli/tracing.rs @@ -3,29 +3,14 @@ use std::option::Option::Some; use std::path::Path; use tracing::subscriber::set_global_default; use tracing::{Event, Level, Subscriber}; -use tracing_subscriber::fmt::format::{DefaultFields, Format}; +use tracing_subscriber::fmt::format::{DefaultFields, Format, JsonFields}; use tracing_subscriber::fmt::time::ChronoLocal; use tracing_subscriber::layer::{Context, SubscriberExt}; use tracing_subscriber::{fmt, EnvFilter, FmtSubscriber, Layer, Registry}; use uuid::Uuid; pub fn init(debug: bool, json: bool, dir: impl AsRef, swap_id: Option) -> Result<()> { - if json { - let level = if debug { Level::DEBUG } else { Level::INFO }; - - let is_terminal = atty::is(atty::Stream::Stderr); - - FmtSubscriber::builder() - .with_env_filter(format!("swap={}", level)) - .with_writer(std::io::stderr) - .with_ansi(is_terminal) - .with_timer(ChronoLocal::with_format("%F %T".to_owned())) - .with_target(false) - .json() - .init(); - - Ok(()) - } else if let Some(swap_id) = swap_id { + if let Some(swap_id) = swap_id { let level_filter = EnvFilter::try_new("swap=debug")?; let registry = Registry::default().with(level_filter); @@ -40,7 +25,19 @@ pub fn init(debug: bool, json: bool, dir: impl AsRef, swap_id: Option, swap_id: Option = tracing_subscriber::fmt::Layer< fn() -> std::io::Stderr, >; +type StdErrJsonLayer = tracing_subscriber::fmt::Layer< + S, + JsonFields, + Format, + fn() -> std::io::Stderr, +>; + fn debug_terminal_printer() -> StdErrPrinter> { let is_terminal = atty::is(atty::Stream::Stderr); StdErrPrinter { @@ -88,6 +96,19 @@ fn debug_terminal_printer() -> StdErrPrinter> { } } +fn debug_json_terminal_printer() -> StdErrPrinter> { + let is_terminal = atty::is(atty::Stream::Stderr); + StdErrPrinter { + inner: fmt::layer() + .with_ansi(is_terminal) + .with_target(false) + .with_timer(ChronoLocal::with_format("%F %T".to_owned())) + .json() + .with_writer(std::io::stderr), + level: Level::DEBUG, + } +} + fn info_terminal_printer() -> StdErrPrinter> { let is_terminal = atty::is(atty::Stream::Stderr); StdErrPrinter { @@ -101,6 +122,20 @@ fn info_terminal_printer() -> StdErrPrinter> { } } +fn info_json_terminal_printer() -> StdErrPrinter> { + let is_terminal = atty::is(atty::Stream::Stderr); + StdErrPrinter { + inner: fmt::layer() + .with_ansi(is_terminal) + .with_target(false) + .with_level(false) + .without_time() + .json() + .with_writer(std::io::stderr), + level: Level::INFO, + } +} + impl Layer for StdErrPrinter where L: 'static + Layer,