Skip to content

Commit

Permalink
chore(logger): abstract logging methods to macros
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon-Becker committed Jan 30, 2024
1 parent 0cf2b6e commit ef83ef6
Show file tree
Hide file tree
Showing 15 changed files with 82 additions and 280 deletions.
10 changes: 2 additions & 8 deletions common/src/ether/selectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ use std::{
use indicatif::ProgressBar;
use tokio::task;

use crate::{
error::Error,
utils::{io::logging::Logger, strings::decode_hex},
};
use crate::{error::Error, info_spinner, utils::strings::decode_hex};

use super::{
evm::core::vm::VM,
Expand Down Expand Up @@ -146,9 +143,6 @@ pub fn resolve_entry_point(evm: &VM, selector: &str) -> u128 {
pub async fn resolve_selectors<T>(selectors: Vec<String>) -> HashMap<String, Vec<T>>
where
T: ResolveSelector + Send + Clone + 'static, {
// get a new logger
let logger = Logger::default();

let resolved_functions: Arc<Mutex<HashMap<String, Vec<T>>>> =
Arc::new(Mutex::new(HashMap::new()));

Expand All @@ -164,7 +158,7 @@ where
resolve_progress
.lock()
.expect("Could not obtain lock on resolve_progress.")
.set_style(logger.info_spinner());
.set_style(info_spinner!());
resolve_progress
.lock()
.expect("Could not obtain lock on resolve_progress.")
Expand Down
12 changes: 3 additions & 9 deletions common/src/resources/transpose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use reqwest::header::HeaderMap;
use serde_json::Value;
use std::time::{Duration, Instant};

use crate::{debug, error, utils::io::logging::Logger, Error};
use crate::{debug, error, info_spinner, Error};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -101,13 +101,10 @@ pub async fn get_transaction_list(
api_key: &str,
bounds: (&u128, &u128),
) -> Result<Vec<(u128, String)>, Error> {
// get a new logger
let logger = Logger::default();

// get a new progress bar
let transaction_list_progress = ProgressBar::new_spinner();
transaction_list_progress.enable_steady_tick(Duration::from_millis(100));
transaction_list_progress.set_style(logger.info_spinner());
transaction_list_progress.set_style(info_spinner!());
transaction_list_progress.set_message(format!("fetching transactions from '{address}' ."));
let start_time = Instant::now();

Expand Down Expand Up @@ -172,13 +169,10 @@ pub async fn get_contract_creation(
address: &str,
api_key: &str,
) -> Option<(u128, String)> {
// get a new logger
let logger = Logger::default();

// get a new progress bar
let transaction_list_progress = ProgressBar::new_spinner();
transaction_list_progress.enable_steady_tick(Duration::from_millis(100));
transaction_list_progress.set_style(logger.info_spinner());
transaction_list_progress.set_style(info_spinner!());
transaction_list_progress.set_message(format!("fetching '{address}''s creation tx ."));
let start_time = Instant::now();

Expand Down
202 changes: 14 additions & 188 deletions common/src/utils/io/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,17 +446,17 @@ impl Default for TraceFactory {

impl Logger {
/// create a new logger with the given verbosity
pub fn new(verbosity: &str) -> (Logger, TraceFactory) {
pub fn new(verbosity: &str) -> Logger {
match verbosity.to_uppercase().as_str() {
"SILENT" => (Logger { level: -1 }, TraceFactory::new(-1)),
"ERROR" => (Logger { level: 0 }, TraceFactory::new(0)),
"WARN" => (Logger { level: 1 }, TraceFactory::new(1)),
"INFO" => (Logger { level: 2 }, TraceFactory::new(2)),
"DEBUG" => (Logger { level: 3 }, TraceFactory::new(3)),
"TRACE" => (Logger { level: 4 }, TraceFactory::new(4)),
"ALL" => (Logger { level: 5 }, TraceFactory::new(5)),
"MAX" => (Logger { level: 6 }, TraceFactory::new(6)),
_ => (Logger { level: 1 }, TraceFactory::new(1)),
"SILENT" => Logger { level: -1 },
"ERROR" => Logger { level: 0 },
"WARN" => Logger { level: 1 },
"INFO" => Logger { level: 2 },
"DEBUG" => Logger { level: 3 },
"TRACE" => Logger { level: 4 },
"ALL" => Logger { level: 5 },
"MAX" => Logger { level: 6 },
_ => Logger { level: 1 },
}
}

Expand Down Expand Up @@ -704,7 +704,8 @@ mod tests {
#[test]
fn test_raw_trace() {
let start_time = Instant::now();
let (logger, mut trace) = Logger::new("TRACE");
let logger = Logger::new("TRACE");
let mut trace = TraceFactory::new(4);

let parent = trace.add("call", 0, 123123, vec!["Test::test_trace()".to_string()]);
trace.add(
Expand Down Expand Up @@ -759,7 +760,8 @@ mod tests {
#[test]
fn test_helper_functions() {
let start_time = Instant::now();
let (logger, mut trace) = Logger::new("TRACE");
let logger = Logger::new("TRACE");
let mut trace = TraceFactory::new(4);

let parent = trace.add_call(
0,
Expand Down Expand Up @@ -803,182 +805,6 @@ mod tests {
logger.info(&format!("Tracing took {}", start_time.elapsed().as_secs_f64()));
}

#[test]
fn test_option() {
let (logger, _) = Logger::new("TRACE");

logger.option(
"warn",
"multiple possibilities",
vec!["option 1".to_string(), "option 2".to_string(), "option 3".to_string()],
Some(0),
true,
);
}

#[test]
fn test_warn() {
let (logger, _) = Logger::new("SILENT");
logger.warn("log");

let (logger, _) = Logger::new("ERROR");
logger.warn("log");

let (logger, _) = Logger::new("WARN");
logger.warn("log");

let (logger, _) = Logger::new("INFO");
logger.warn("log");

let (logger, _) = Logger::new("DEBUG");
logger.warn("log");

let (logger, _) = Logger::new("TRACE");
logger.warn("log");

let (logger, _) = Logger::new("ALL");
logger.warn("log");

let (logger, _) = Logger::new("MAX");
logger.warn("log");
}

#[test]
fn test_error() {
let (logger, _) = Logger::new("SILENT");
logger.error("log");

let (logger, _) = Logger::new("ERROR");
logger.error("log");

let (logger, _) = Logger::new("WARN");
logger.error("log");

let (logger, _) = Logger::new("INFO");
logger.error("log");

let (logger, _) = Logger::new("DEBUG");
logger.error("log");

let (logger, _) = Logger::new("TRACE");
logger.error("log");

let (logger, _) = Logger::new("ALL");
logger.error("log");

let (logger, _) = Logger::new("MAX");
logger.error("log");
}

#[test]
fn test_info() {
let (logger, _) = Logger::new("SILENT");
logger.info("log");

let (logger, _) = Logger::new("ERROR");
logger.info("log");

let (logger, _) = Logger::new("WARN");
logger.info("log");

let (logger, _) = Logger::new("INFO");
logger.info("log");

let (logger, _) = Logger::new("DEBUG");
logger.info("log");

let (logger, _) = Logger::new("TRACE");
logger.info("log");

let (logger, _) = Logger::new("ALL");
logger.info("log");

let (logger, _) = Logger::new("MAX");
logger.info("log");
}

#[test]
fn test_success() {
let (logger, _) = Logger::new("SILENT");
logger.success("log");

let (logger, _) = Logger::new("ERROR");
logger.success("log");

let (logger, _) = Logger::new("WARN");
logger.success("log");

let (logger, _) = Logger::new("INFO");
logger.success("log");

let (logger, _) = Logger::new("DEBUG");
logger.success("log");

let (logger, _) = Logger::new("TRACE");
logger.success("log");

let (logger, _) = Logger::new("ALL");
logger.success("log");

let (logger, _) = Logger::new("MAX");
logger.success("log");
}

#[test]
fn test_debug() {
let (logger, _) = Logger::new("SILENT");
logger.debug("log");

let (logger, _) = Logger::new("ERROR");
logger.debug("log");

let (logger, _) = Logger::new("WARN");
logger.debug("log");

let (logger, _) = Logger::new("INFO");
logger.debug("log");

let (logger, _) = Logger::new("DEBUG");
logger.debug("log");

let (logger, _) = Logger::new("TRACE");
logger.debug("log");

let (logger, _) = Logger::new("ALL");
logger.debug("log");

let (logger, _) = Logger::new("MAX");
logger.debug("log");
}

#[test]
fn test_max() {
let (_logger, _) = Logger::new("SILENT");
use crate::debug_max;
debug_max!("log");

let (_logger, _) = Logger::new("ERROR");
debug_max!("log");

let (_logger, _) = Logger::new("WARN");
debug_max!("log");

let (_logger, _) = Logger::new("INFO");
debug_max!("log");

let (_logger, _) = Logger::new("DEBUG");
debug_max!("log");

let (_logger, _) = Logger::new("TRACE");
debug_max!("log");

let (_logger, _) = Logger::new("ALL");
debug_max!("log");

let (_logger, _) = Logger::new("MAX");
debug_max!("log");
}

#[test]
fn test_set_logger_env_default() {
env::remove_var("RUST_LOG");
Expand Down
28 changes: 28 additions & 0 deletions common/src/utils/io/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,31 @@ macro_rules! fatal {
$crate::log_helper!(fatal, $message, $($arg)*)
};
}

#[macro_export]
macro_rules! info_spinner {
() => {
indicatif::ProgressStyle::with_template(&format!(
"{} {}: {}",
colored::Colorize::dimmed($crate::utils::time::pretty_timestamp().as_str()),
colored::Colorize::bright_cyan(colored::Colorize::bold("info")),
"{spinner} {msg}"
))
.expect("Failed to create spinner.")
.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
};
}

#[macro_export]
macro_rules! debug_spinner {
() => {
indicatif::ProgressStyle::with_template(&format!(
"{} {}: {}",
colored::Colorize::dimmed($crate::utils::time::pretty_timestamp().as_str()),
colored::Colorize::bright_magenta(colored::Colorize::bold("debug")),
"{spinner} {msg}"
))
.expect("Failed to create spinner.")
.tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")
};
}
7 changes: 2 additions & 5 deletions common/src/utils/range_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ impl RangeMap {
self.0.insert(range, opcode);
} else {
incumbents.iter().for_each(|incumbent| {
if incumbent.end < range.start {
} else if incumbent.start > range.end {
} else {
if incumbent.start <= range.end && incumbent.end >= range.start {
// Case 1: overlapping
if range.start <= incumbent.start && range.end >= incumbent.end {
// newInterval completely covers incumbent
Expand Down Expand Up @@ -66,8 +64,7 @@ impl RangeMap {
self.0.insert(left, old_opcode.clone());
self.0.insert(right, old_opcode.clone());
} else {
// raise an error: this should be impossible
assert!(false, "range_map::write: impossible case");
panic!("range_map::write: impossible case");
}
}
self.0.insert(range.clone(), opcode.clone());
Expand Down
10 changes: 3 additions & 7 deletions core/src/cfg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use heimdall_common::{
compiler::{detect_compiler, Compiler},
selectors::find_function_selectors,
},
info,
info, info_spinner,
utils::{
strings::{encode_hex, StringExt},
threading::run_with_timeout,
Expand Down Expand Up @@ -93,11 +93,7 @@ pub async fn cfg(args: CFGArgs) -> Result<Graph<String, String>, Error> {
let now = Instant::now();

set_logger_env(&args.verbose);

let (logger, mut trace) = Logger::new(match args.verbose.log_level() {
Some(level) => level.as_str(),
None => "SILENT",
});
let mut trace = TraceFactory::default();

// add the call to the trace
let cfg_call = trace.add_call(
Expand Down Expand Up @@ -182,7 +178,7 @@ pub async fn cfg(args: CFGArgs) -> Result<Graph<String, String>, Error> {
// create a new progress bar
let progress = ProgressBar::new_spinner();
progress.enable_steady_tick(Duration::from_millis(100));
progress.set_style(logger.info_spinner());
progress.set_style(info_spinner!());

// create a new petgraph StableGraph
let mut contract_cfg = Graph::<String, String>::new();
Expand Down
Loading

0 comments on commit ef83ef6

Please sign in to comment.