Skip to content

Commit

Permalink
feat: Add simplelog (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
nbaztec authored Sep 13, 2023
1 parent bb544a4 commit 0cac26b
Show file tree
Hide file tree
Showing 10 changed files with 206 additions and 105 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ etc/**/*.zbin
!.vscode/extensions.json
!.vscode/launch.json
!.vscode/tasks.json

*.log
28 changes: 26 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,6 @@ serde_json = "1.0.67"
bigdecimal = { version = "0.2.0" }
hex = "0.4"
ethabi = "16.0.0"
itertools = "0.10.5"
itertools = "0.10.5"
log = "0.4.20"
simplelog = "0.12.1"
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,17 @@ Please note that `era-test-node` is still in its **alpha** stage. Some features
```bash
era_test_node run
```
## 📃 Logging

The node may be started in either of `debug`, `info`, `warn` or `error` logging levels via the `--log` option:
```bash
era_test_node --log=error run
```

Additionally, the file path can be provided via the `--log-file-path` option (defaults to `./era_test_node.log`):
```bash
era_test_node --log=error --log-file-path=run.log run
```

## 🌐 Network Details

Expand Down
2 changes: 1 addition & 1 deletion src/console_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,6 @@ impl ConsoleLogHandler {
tokens.iter().map(|t| format!("{}", t)).join(" ")
})
});
println!("{}", message.cyan());
log::info!("{}", message.cyan());
}
}
4 changes: 2 additions & 2 deletions src/fork.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl<S: ForkSource> ForkStorage<S> {
.as_ref()
.and_then(|d| d.overwrite_chain_id)
.unwrap_or(L2ChainId(TEST_NODE_NETWORK_ID));
println!("Starting network with chain id: {:?}", chain_id);
log::info!("Starting network with chain id: {:?}", chain_id);

ForkStorage {
inner: Arc::new(RwLock::new(ForkStorageInner {
Expand Down Expand Up @@ -239,7 +239,7 @@ impl ForkDetails<HttpForkSource> {

let l1_batch_number = block_details.l1_batch_number;

println!(
log::info!(
"Creating fork from {:?} L1 block: {:?} L2 block: {:?} with timestamp {:?} and L1 gas price {:?}",
url, l1_batch_number, miniblock, block_details.base.timestamp, block_details.base.l1_gas_price,
);
Expand Down
44 changes: 24 additions & 20 deletions src/formatter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub fn print_event(event: &VmEvent, resolve_hashes: bool) {
}
}

println!(
log::info!(
"{} {}",
address_to_human_readable(event.address)
.map(|x| format!("{:42}", x.blue()))
Expand Down Expand Up @@ -150,9 +150,9 @@ pub fn print_call(call: &Call, padding: usize, show_calls: &ShowCalls, resolve_h
);

if call.revert_reason.as_ref().is_some() || call.error.as_ref().is_some() {
println!("{}", pretty_print.on_red());
log::info!("{}", pretty_print.on_red());
} else {
println!("{}", pretty_print);
log::info!("{}", pretty_print);
}
}
for subcall in &call.calls {
Expand All @@ -162,44 +162,48 @@ pub fn print_call(call: &Call, padding: usize, show_calls: &ShowCalls, resolve_h

pub fn print_logs(log_query: &StorageLogQuery) {
let separator = "─".repeat(82);
println!("{:<15} {:?}", "Type:", log_query.log_type);
println!(
log::info!("{:<15} {:?}", "Type:", log_query.log_type);
log::info!(
"{:<15} {}",
"Address:",
address_to_human_readable(log_query.log_query.address)
.unwrap_or(format!("{}", log_query.log_query.address))
);
println!("{:<15} {:#066x}", "Key:", log_query.log_query.key);
log::info!("{:<15} {:#066x}", "Key:", log_query.log_query.key);

println!(
log::info!(
"{:<15} {:#066x}",
"Read Value:", log_query.log_query.read_value
"Read Value:",
log_query.log_query.read_value
);

if log_query.log_type != StorageLogQueryType::Read {
println!(
log::info!(
"{:<15} {:#066x}",
"Written Value:", log_query.log_query.written_value
"Written Value:",
log_query.log_query.written_value
);
}
println!("{}", separator);
log::info!("{}", separator);
}

pub fn print_vm_details(result: &VmPartialExecutionResult) {
println!("\n┌──────────────────────────┐");
println!("│ VM EXECUTION RESULTS │");
println!("└──────────────────────────┘");
log::info!("");
log::info!("┌──────────────────────────┐");
log::info!("│ VM EXECUTION RESULTS │");
log::info!("└──────────────────────────┘");

println!("Cycles Used: {}", result.cycles_used);
println!("Computation Gas Used: {}", result.computational_gas_used);
println!("Contracts Used: {}", result.contracts_used);
log::info!("Cycles Used: {}", result.cycles_used);
log::info!("Computation Gas Used: {}", result.computational_gas_used);
log::info!("Contracts Used: {}", result.contracts_used);

if let Some(revert_reason) = &result.revert_reason {
println!(
log::info!("");
log::info!(
"{}",
format!("\n[!] Revert Reason: {}", revert_reason).on_red()
format!("[!] Revert Reason: {}", revert_reason).on_red()
);
}

println!("════════════════════════════");
log::info!("════════════════════════════");
}
72 changes: 62 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::hardhat::{HardhatNamespaceImpl, HardhatNamespaceT};
use crate::node::{ShowGasDetails, ShowStorageLogs, ShowVMDetails};
use clap::{Parser, Subcommand};
use clap::{Parser, Subcommand, ValueEnum};
use configuration_api::ConfigurationApiNamespaceT;
use evm::{EvmNamespaceImpl, EvmNamespaceT};
use fork::{ForkDetails, ForkSource};
use node::ShowCalls;
use simplelog::{
ColorChoice, CombinedLogger, ConfigBuilder, LevelFilter, TermLogger, TerminalMode, WriteLogger,
};
use zks::ZkMockNamespaceImpl;

mod bootloader_debug;
Expand All @@ -27,6 +30,7 @@ use zksync_core::api_server::web3::namespaces::NetNamespace;

use std::{
env,
fs::File,
net::{IpAddr, Ipv4Addr, SocketAddr},
str::FromStr,
};
Expand Down Expand Up @@ -135,6 +139,26 @@ async fn build_json_http<
tokio::spawn(recv.map(drop))
}

/// Log filter level for the node.
#[derive(Debug, Clone, ValueEnum)]
enum LogLevel {
Debug,
Info,
Warn,
Error,
}

impl From<LogLevel> for LevelFilter {
fn from(value: LogLevel) -> Self {
match value {
LogLevel::Debug => LevelFilter::Debug,
LogLevel::Info => LevelFilter::Info,
LogLevel::Warn => LevelFilter::Warn,
LogLevel::Error => LevelFilter::Error,
}
}
}

#[derive(Debug, Parser)]
#[command(author = "Matter Labs", version, about = "Test Node", long_about = None)]
struct Cli {
Expand Down Expand Up @@ -165,6 +189,14 @@ struct Cli {
#[arg(long)]
/// If true, will load the locally compiled system contracts (useful when doing changes to system contracts or bootloader)
dev_use_local_contracts: bool,

/// Log filter level - default: info
#[arg(long, default_value = "info")]
log: LogLevel,

/// Log file path - default: era_test_node.log
#[arg(long, default_value = "era_test_node.log")]
log_file_path: String,
}

#[derive(Debug, Subcommand)]
Expand Down Expand Up @@ -210,14 +242,33 @@ struct ReplayArgs {
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let opt = Cli::parse();
let filter = EnvFilter::from_default_env();

let log_level_filter = LevelFilter::from(opt.log);
let log_config = ConfigBuilder::new()
.add_filter_allow_str("era_test_node")
.build();
CombinedLogger::init(vec![
TermLogger::new(
log_level_filter,
log_config.clone(),
TerminalMode::Mixed,
ColorChoice::Auto,
),
WriteLogger::new(
log_level_filter,
log_config,
File::create(opt.log_file_path).unwrap(),
),
])
.expect("failed instantiating logger");

if opt.dev_use_local_contracts {
if let Some(path) = env::var_os("ZKSYNC_HOME") {
println!("+++++ Reading local contracts from {:?} +++++", path);
log::info!("+++++ Reading local contracts from {:?} +++++", path);
}
}

let filter = EnvFilter::from_default_env();
let subscriber = FmtSubscriber::builder()
.with_max_level(Level::TRACE)
.with_env_filter(filter)
Expand Down Expand Up @@ -265,14 +316,15 @@ async fn main() -> anyhow::Result<()> {
let _ = node.apply_txs(transactions_to_replay);
}

println!("\nRich Accounts");
println!("=============");
log::info!("Rich Accounts");
log::info!("=============");
for (index, wallet) in RICH_WALLETS.iter().enumerate() {
let address = wallet.0;
let private_key = wallet.1;
node.set_rich_account(H160::from_str(address).unwrap());
println!("Account #{}: {} (1_000_000_000_000 ETH)", index, address);
println!("Private Key: {}\n", private_key);
log::info!("Account #{}: {} (1_000_000_000_000 ETH)", index, address);
log::info!("Private Key: {}", private_key);
log::info!("");
}

let net = NetNamespace::new(L2ChainId(TEST_NODE_NETWORK_ID));
Expand All @@ -292,9 +344,9 @@ async fn main() -> anyhow::Result<()> {
)
.await;

println!("========================================");
println!(" Node is ready at 127.0.0.1:{}", opt.port);
println!("========================================");
log::info!("========================================");
log::info!(" Node is ready at 127.0.0.1:{}", opt.port);
log::info!("========================================");

future::select_all(vec![threads]).await.0.unwrap();

Expand Down
Loading

0 comments on commit 0cac26b

Please sign in to comment.