feat: introduce logging

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
Kasper Juul Hermansen 2023-09-24 13:51:35 +02:00
parent 38f36f1aa5
commit 09dfa6c2e3
Signed by: kjuulh
GPG Key ID: 9AA7BC13CE474394
7 changed files with 82 additions and 38 deletions

2
Cargo.lock generated
View File

@ -538,6 +538,7 @@ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
"clap 4.4.4", "clap 4.4.4",
"crunch-file",
"thiserror", "thiserror",
"tokio", "tokio",
"tracing", "tracing",
@ -572,6 +573,7 @@ dependencies = [
"serde", "serde",
"tokio", "tokio",
"toml_edit", "toml_edit",
"tracing",
] ]
[[package]] [[package]]

View File

@ -8,6 +8,7 @@ crunch-traits = { path = "crates/crunch-traits" }
crunch-envelope = { path = "crates/crunch-envelope" } crunch-envelope = { path = "crates/crunch-envelope" }
crunch-in-memory = { path = "crates/crunch-in-memory" } crunch-in-memory = { path = "crates/crunch-in-memory" }
crunch-nats = { path = "crates/crunch-nats" } crunch-nats = { path = "crates/crunch-nats" }
crunch-file = {path = "crates/crunch-file"}
anyhow = { version = "1.0.71" } anyhow = { version = "1.0.71" }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }

View File

@ -6,6 +6,8 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
crunch-file.workspace = true
anyhow.workspace = true anyhow.workspace = true
tracing.workspace = true tracing.workspace = true
tokio.workspace = true tokio.workspace = true

View File

@ -0,0 +1,41 @@
use clap::ValueEnum;
use tracing::Level;
#[derive(Clone, ValueEnum)]
pub enum LogArg {
None,
Trace,
Debug,
Info,
Warn,
Error,
}
impl LogArg {
pub fn init_logging(&self) {
match self {
LogArg::None => {}
LogArg::Trace => {
tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.init();
}
LogArg::Debug => {
tracing_subscriber::fmt()
.with_max_level(Level::DEBUG)
.init();
}
LogArg::Info => {
tracing_subscriber::fmt().with_max_level(Level::INFO).init();
}
LogArg::Warn => {
tracing_subscriber::fmt().with_max_level(Level::WARN).init();
}
LogArg::Error => {
tracing_subscriber::fmt()
.with_max_level(Level::ERROR)
.init();
}
}
}
}

View File

@ -1,4 +1,10 @@
mod logging;
use std::path::PathBuf;
use anyhow::anyhow;
use clap::{Args, Parser, Subcommand, ValueEnum}; use clap::{Args, Parser, Subcommand, ValueEnum};
use logging::LogArg;
use tracing::Level; use tracing::Level;
#[derive(Parser, Clone)] #[derive(Parser, Clone)]
@ -27,52 +33,33 @@ struct GlobalArgs {
global = true, global = true,
help_heading = "Global" help_heading = "Global"
)] )]
crunch_file: String, crunch_file: PathBuf,
}
#[derive(Clone, ValueEnum)]
enum LogArg {
None,
Trace,
Debug,
Info,
Warn,
Error,
} }
#[tokio::main] #[tokio::main]
async fn main() { async fn main() -> anyhow::Result<()> {
let cli = Cli::parse(); let cli = Cli::parse();
init_logging(&cli.global_args.log); cli.global_args.log.init_logging();
match &cli.commands { match &cli.commands {
Commands::Generate {} => {} Commands::Generate {} => {
let config_file = config::get_file(&cli.global_args.crunch_file)
.await
.map_err(|e| anyhow!("failed to load config: {}", e))?
.get_config()
.map_err(|e| anyhow!("invalid config: {}", e))?;
tracing::info!("generating crunch code")
} }
}
Ok(())
} }
fn init_logging(log: &LogArg) { mod config {
match log { pub async fn get_file(path: &std::path::Path) -> anyhow::Result<crunch_file::File> {
LogArg::None => {} let file = crunch_file::File::parse_file(path).await?;
LogArg::Trace => {
tracing_subscriber::fmt() Ok(file)
.with_max_level(Level::TRACE)
.init();
}
LogArg::Debug => {
tracing_subscriber::fmt()
.with_max_level(Level::DEBUG)
.init();
}
LogArg::Info => {
tracing_subscriber::fmt().with_max_level(Level::INFO).init();
}
LogArg::Warn => {
tracing_subscriber::fmt().with_max_level(Level::WARN).init();
}
LogArg::Error => {
tracing_subscriber::fmt()
.with_max_level(Level::ERROR)
.init();
}
} }
} }

View File

@ -13,6 +13,7 @@ tokio.workspace = true
async-trait.workspace = true async-trait.workspace = true
toml_edit.workspace = true toml_edit.workspace = true
serde.workspace = true serde.workspace = true
tracing.workspace = true
[dev-dependencies] [dev-dependencies]
pretty_assertions.workspace = true pretty_assertions.workspace = true

View File

@ -31,12 +31,15 @@ pub struct Publish {
#[allow(dead_code)] #[allow(dead_code)]
impl File { impl File {
pub async fn parse_file(path: &std::path::Path) -> anyhow::Result<File> { pub async fn parse_file(path: &std::path::Path) -> anyhow::Result<File> {
tracing::debug!("loading crunch file at: {}", path.display());
let file = tokio::fs::read_to_string(path).await?; let file = tokio::fs::read_to_string(path).await?;
Self::parse(&file).await Self::parse(&file).await
} }
pub async fn parse(content: &str) -> anyhow::Result<File> { pub async fn parse(content: &str) -> anyhow::Result<File> {
tracing::debug!("parsing crunch file");
let config: Document = content.parse::<Document>()?; let config: Document = content.parse::<Document>()?;
Ok(File { doc: config }) Ok(File { doc: config })
@ -44,6 +47,8 @@ impl File {
pub async fn write_file(&self, path: &std::path::Path) -> anyhow::Result<()> { pub async fn write_file(&self, path: &std::path::Path) -> anyhow::Result<()> {
let content = self.write().await?; let content = self.write().await?;
tracing::debug!("writing to file: {}", path.display());
let mut file = tokio::fs::File::create(path).await?; let mut file = tokio::fs::File::create(path).await?;
file.write_all(content.as_bytes()).await?; file.write_all(content.as_bytes()).await?;
@ -53,6 +58,8 @@ impl File {
} }
pub async fn write(&self) -> anyhow::Result<String> { pub async fn write(&self) -> anyhow::Result<String> {
tracing::debug!("converting crunch config into file");
let content = self.doc.to_string(); let content = self.doc.to_string();
Ok(content) Ok(content)
@ -64,9 +71,11 @@ impl File {
publish["output-path"] = value(output_path); publish["output-path"] = value(output_path);
if !self.doc.contains_key("publish") { if !self.doc.contains_key("publish") {
tracing::debug!("publish key not existing, adding new");
self.doc["publish"] = toml_edit::array() self.doc["publish"] = toml_edit::array()
} }
tracing::debug!("adding new publish item");
self.doc["publish"] self.doc["publish"]
.as_array_of_tables_mut() .as_array_of_tables_mut()
.expect("publish to be present and be array of tables [[publish]]") .expect("publish to be present and be array of tables [[publish]]")
@ -78,6 +87,7 @@ impl File {
pub fn get_config(&self) -> anyhow::Result<Config> { pub fn get_config(&self) -> anyhow::Result<Config> {
let content = self.doc.to_string(); let content = self.doc.to_string();
tracing::debug!("converting config into read only copy");
let config: Config = toml_edit::de::from_str(&content)?; let config: Config = toml_edit::de::from_str(&content)?;
Ok(config) Ok(config)