Skip to content

Commit

Permalink
feat: add logs for incoming API requests
Browse files Browse the repository at this point in the history
  • Loading branch information
MexicanAce committed Sep 15, 2023
1 parent be53aec commit c637672
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "era_test_node"
version = "0.1.0"
version = "0.1.0-alpha.3"
edition = "2018"
authors = ["The Matter Labs Team <[email protected]>"]
homepage = "https://zksync.io/"
Expand Down
99 changes: 99 additions & 0 deletions src/logging_middleware.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use colored::Colorize;
use itertools::Itertools;
use jsonrpc_core::{Middleware, Metadata, Request, Response, middleware, FutureResponse, Call, Params};
use futures::future::Either;
use futures::Future;
use log::LevelFilter;

#[derive(Clone, Debug, Default)]
pub struct Meta();
impl Metadata for Meta {}

pub struct LoggingMiddleware {
log_level_filter: LevelFilter,
}

impl LoggingMiddleware {
pub fn new(log_level_filter: LevelFilter) -> Self {
Self { log_level_filter }
}
}

/// Logging Middleware for all in-bound requests
/// Logs out incoming requests and their parameters
/// Useful for debugging applications that are pointed at this service
impl Middleware<Meta> for LoggingMiddleware {
type Future = FutureResponse;
type CallFuture = middleware::NoopCallFuture;

fn on_request<F, X>(&self, request: Request, meta: Meta, next: F) -> Either<Self::Future, X>
where
F: FnOnce(Request, Meta) -> X + Send,
X: Future<Output = Option<Response>> + Send + 'static,
{
match &request {
Request::Single(call) => {
match call {
Call::MethodCall(method_call) => {
match self.log_level_filter {
LevelFilter::Debug => {
let full_params = match &method_call.params {
Params::Array(values) => {
if values.len() == 0 {
String::default()
} else {
format!("with [{}]", values.iter().join(", "))
}

},
_ => String::default()
};

log::debug!(
"{} was called {}",
method_call.method.cyan(),
full_params);
},
_ => {
// Generate truncated params for requests with massive payloads
let truncated_params = match &method_call.params {
Params::Array(values) => {
if values.len() == 0 {
String::default()
} else {
format!("with [{}]",
values
.iter()
.map(|s| {
let s_str = s.to_string();
if s_str.len() > 70 {
format!("{:.67}...", s_str)
} else {
s_str
}
})
.collect::<Vec<String>>()
.join(", ")
)
}

},
_ => String::default()
};

log::info!(
"{} was called {}",
method_call.method.cyan(),
truncated_params);
}
}
},
_ => {}
}
},
_ => {}
};

Either::Left(Box::pin(next(request, meta)))
}
}
10 changes: 7 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use clap::{Parser, Subcommand, ValueEnum};
use configuration_api::ConfigurationApiNamespaceT;
use evm::{EvmNamespaceImpl, EvmNamespaceT};
use fork::{ForkDetails, ForkSource};
use logging_middleware::LoggingMiddleware;
use node::ShowCalls;
use simplelog::{
ColorChoice, CombinedLogger, ConfigBuilder, LevelFilter, TermLogger, TerminalMode, WriteLogger,
Expand All @@ -19,6 +20,7 @@ mod fork;
mod formatter;
mod hardhat;
mod http_fork_source;
mod logging_middleware;
mod node;
mod resolver;
mod system_contracts;
Expand All @@ -44,7 +46,7 @@ use futures::{
future::{self},
FutureExt,
};
use jsonrpc_core::IoHandler;
use jsonrpc_core::MetaIoHandler;
use zksync_basic_types::{L2ChainId, H160, H256};

use crate::{configuration_api::ConfigurationApiNamespace, node::TEST_NODE_NETWORK_ID};
Expand Down Expand Up @@ -100,6 +102,7 @@ async fn build_json_http<
S: std::marker::Sync + std::marker::Send + 'static + ForkSource + std::fmt::Debug,
>(
addr: SocketAddr,
log_level_filter: LevelFilter,
node: InMemoryNode<S>,
net: NetNamespace,
config_api: ConfigurationApiNamespace<S>,
Expand All @@ -110,7 +113,7 @@ async fn build_json_http<
let (sender, recv) = oneshot::channel::<()>();

let io_handler = {
let mut io = IoHandler::new();
let mut io = MetaIoHandler::with_middleware(LoggingMiddleware::new(log_level_filter));
io.extend_with(node.to_delegate());
io.extend_with(net.to_delegate());
io.extend_with(config_api.to_delegate());
Expand Down Expand Up @@ -335,7 +338,8 @@ async fn main() -> anyhow::Result<()> {
let hardhat = HardhatNamespaceImpl::new(node.get_inner());

let threads = build_json_http(
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), opt.port),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), opt.port),
log_level_filter,
node,
net,
config_api,
Expand Down
2 changes: 1 addition & 1 deletion src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ impl<S: std::fmt::Debug + ForkSource> InMemoryNodeInner<S> {
fn not_implemented<T: Send + 'static>(
method_name: &str,
) -> jsonrpc_core::BoxFuture<Result<T, jsonrpc_core::Error>> {
log::info!("Method {} is not implemented", method_name);
log::info!("{}", format!("Method {} is not implemented", method_name).yellow());
Err(jsonrpc_core::Error {
data: None,
code: jsonrpc_core::ErrorCode::MethodNotFound,
Expand Down

0 comments on commit c637672

Please sign in to comment.