Fix #183: support structured log for sim app. (#184)

This commit is contained in:
Al Liu 2023-06-16 19:26:48 +08:00 committed by GitHub
parent 285f899c8a
commit 40048fa47b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 53 additions and 13 deletions

View File

@ -5,7 +5,7 @@ edition = "2021"
[[bin]]
name = "simulation"
path = "src/bin/app.rs"
path = "src/bin/app/main.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -0,0 +1,47 @@
use std::str::FromStr;
#[derive(Copy, Clone)]
pub enum LogFormat {
Plain,
Json,
}
impl FromStr for LogFormat {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"json" => Ok(LogFormat::Json),
"plain" => Ok(LogFormat::Plain),
_ => Err(anyhow::anyhow!("Unknown log format")),
}
}
}
pub fn config_tracing(fmt: Option<LogFormat>) {
let filter = std::env::var("SIMULATION_LOG").unwrap_or_else(|_| "info".to_owned());
if let Some(LogFormat::Json) = fmt {
let subscriber = tracing_subscriber::fmt::fmt()
.without_time()
.with_line_number(true)
.with_env_filter(filter)
.with_file(false)
.with_target(true)
.with_ansi(true)
.json()
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("config_tracing is only called once");
} else {
let subscriber = tracing_subscriber::fmt::fmt()
.without_time()
.with_line_number(true)
.with_env_filter(filter)
.with_file(false)
.with_target(true)
.with_ansi(true)
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("config_tracing is only called once");
}
}

View File

@ -33,6 +33,7 @@ use simulations::{
node::carnot::CarnotNode, output_processors::OutData, runner::SimulationRunner,
settings::SimulationSettings, util::node_id,
};
mod log;
/// Main simulation wrapper
/// Pipes together the cli arguments with the execution
@ -43,6 +44,8 @@ pub struct SimulationApp {
input_settings: PathBuf,
#[clap(long)]
stream_type: Option<StreamType>,
#[clap(long)]
log_format: Option<log::LogFormat>,
}
impl SimulationApp {
@ -50,6 +53,7 @@ impl SimulationApp {
let Self {
input_settings,
stream_type,
log_format: _,
} = self;
let simulation_settings: SimulationSettings = load_json_from_file(&input_settings)?;
@ -221,19 +225,8 @@ fn generate_overlays<R: Rng>(
}
fn main() -> anyhow::Result<()> {
let filter = std::env::var("SIMULATION_LOG").unwrap_or_else(|_| "info".to_owned());
let subscriber = tracing_subscriber::fmt::fmt()
.without_time()
.with_line_number(true)
.with_env_filter(filter)
.with_file(false)
.with_target(true)
.with_ansi(true)
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("config_tracing is only called once");
let app: SimulationApp = SimulationApp::parse();
log::config_tracing(app.log_format);
if let Err(e) = app.run() {
tracing::error!("error: {}", e);