Skip to content

Commit 79e14e0

Browse files
committed
server/json-rpc: Add request logging middleware
Because of limitations in the jsonrpsee API, it's not possible to log HTTP request information and the actual JSON-RPC payload in one log message; but the two log messages should appear right next to each other. Logging both together would require a more complex upgrade to a newer jsonrpsee version.
1 parent dc8afd0 commit 79e14e0

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

server/json-rpc/src/lib.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use graph::prelude::{Value as GraphValue, *};
2+
use jsonrpsee::core::middleware::{Headers, HttpMiddleware, MethodKind, Params};
23
use jsonrpsee::core::Error as JsonRpcError;
34
use jsonrpsee::http_server::{HttpServerBuilder, HttpServerHandle};
45
use jsonrpsee::types::error::CallError;
@@ -9,6 +10,43 @@ use serde_json::{self, Value as JsonValue};
910
use std::collections::BTreeMap;
1011
use std::net::{Ipv4Addr, SocketAddr};
1112

13+
/// Middleware for logging JSON-RPC requests.
14+
///
15+
/// Logs incoming HTTP requests with remote address and proxy headers,
16+
/// and logs each JSON-RPC method call with its parameters.
17+
#[derive(Clone)]
18+
struct RpcLogger {
19+
logger: Logger,
20+
}
21+
22+
impl HttpMiddleware for RpcLogger {
23+
type Instant = ();
24+
25+
fn on_request(&self, remote_addr: SocketAddr, headers: &Headers) -> Self::Instant {
26+
info!(
27+
&self.logger,
28+
"JSON-RPC request";
29+
"remote_addr" => %remote_addr,
30+
"x_forwarded_for" => headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()),
31+
"x_real_ip" => headers.get("x-real-ip").and_then(|v| v.to_str().ok()),
32+
"x_forwarded_proto" => headers.get("x-forwarded-proto").and_then(|v| v.to_str().ok())
33+
);
34+
}
35+
36+
fn on_call(&self, method_name: &str, params: Params, _kind: MethodKind) {
37+
info!(
38+
&self.logger,
39+
"JSON-RPC call";
40+
"method" => method_name,
41+
"params" => ?params
42+
);
43+
}
44+
45+
fn on_result(&self, _method_name: &str, _success: bool, _started_at: Self::Instant) {}
46+
47+
fn on_response(&self, _result: &str, _started_at: Self::Instant) {}
48+
}
49+
1250
type JsonRpcResult<T> = Result<T, jsonrpsee::core::Error>;
1351

1452
pub struct JsonRpcServer {
@@ -43,7 +81,12 @@ impl JsonRpcServer {
4381
};
4482

4583
let socket_addr: SocketAddr = (Ipv4Addr::new(0, 0, 0, 0), port).into();
46-
let http_server = HttpServerBuilder::default().build(socket_addr).await?;
84+
let http_server = HttpServerBuilder::default()
85+
.set_middleware(RpcLogger {
86+
logger: state.logger.clone(),
87+
})
88+
.build(socket_addr)
89+
.await?;
4790

4891
let mut rpc_module = RpcModule::new(state);
4992
rpc_module

0 commit comments

Comments
 (0)