Skip to content

Commit

Permalink
chore(infra): add dynamic logging util fn
Browse files Browse the repository at this point in the history
commit-id:9ffe9fbe
  • Loading branch information
Itay-Tsabary-Starkware committed Nov 28, 2024
1 parent 6f268c8 commit 3074675
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 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 crates/infra_utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ workspace = true

[dependencies]
tokio = { workspace = true, features = ["process"] }
tracing.workspace = true

[dev-dependencies]
rstest.workspace = true
tokio = { workspace = true, features = ["macros", "rt"] }
1 change: 1 addition & 0 deletions crates/infra_utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod command;
pub mod path;
pub mod tracing;
40 changes: 40 additions & 0 deletions crates/infra_utils/src/tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use tracing::{debug, error, info, trace, warn};

/// Dynamically set tracing level of a message.
pub struct DynamicLogger {
level: TraceLevel,
base_message: Option<String>,
}

impl DynamicLogger {
/// Creates a new trace configuration
pub fn new(level: TraceLevel, base_message: Option<String>) -> Self {
Self { level, base_message }
}

/// Logs a given message at the specified tracing level, concatenated with the base message if
/// it exists.
pub fn log_message(&self, message: &str) {
let message = match &self.base_message {
Some(base_message) => format!("{}: {}", base_message, message),
None => message.to_string(),
};

match self.level {
TraceLevel::Trace => trace!(message),
TraceLevel::Debug => debug!(message),
TraceLevel::Info => info!(message),
TraceLevel::Warn => warn!(message),
TraceLevel::Error => error!(message),
}
}
}

#[derive(Clone, Copy)]
pub enum TraceLevel {
Trace,
Debug,
Info,
Warn,
Error,
}

0 comments on commit 3074675

Please sign in to comment.