jsonrpsee_core/middleware/layer/
logger.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! RPC Logger layer.
28
29use crate::middleware::{Batch, Notification, RpcServiceT};
30use crate::traits::ToJson;
31
32use futures_util::Future;
33use jsonrpsee_types::Request;
34use serde_json::value::RawValue;
35use tracing::Instrument;
36
37/// RPC logger layer.
38#[derive(Copy, Clone, Debug)]
39pub struct RpcLoggerLayer(u32);
40
41impl RpcLoggerLayer {
42	/// Create a new logging layer.
43	pub fn new(max: u32) -> Self {
44		Self(max)
45	}
46}
47
48impl<S> tower::Layer<S> for RpcLoggerLayer {
49	type Service = RpcLogger<S>;
50
51	fn layer(&self, service: S) -> Self::Service {
52		RpcLogger { service, max: self.0 }
53	}
54}
55
56/// A middleware that logs each RPC call and response.
57#[derive(Debug, Clone)]
58pub struct RpcLogger<S> {
59	max: u32,
60	service: S,
61}
62
63impl<S> RpcServiceT for RpcLogger<S>
64where
65	S: RpcServiceT + Send + Sync + Clone + 'static,
66	S::MethodResponse: ToJson,
67	S::BatchResponse: ToJson,
68{
69	type MethodResponse = S::MethodResponse;
70	type NotificationResponse = S::NotificationResponse;
71	type BatchResponse = S::BatchResponse;
72
73	#[tracing::instrument(name = "method_call", skip_all, fields(method = request.method_name()), level = "trace")]
74	fn call<'a>(&self, request: Request<'a>) -> impl Future<Output = Self::MethodResponse> + Send + 'a {
75		let json = serde_json::value::to_raw_value(&request);
76		let json_str = unwrap_json_str_or_invalid(&json);
77		tracing::trace!(target: "jsonrpsee", "request = {}", truncate_at_char_boundary(json_str, self.max as usize));
78
79		let service = self.service.clone();
80		let max = self.max;
81
82		async move {
83			let rp = service.call(request).await;
84
85			let json = rp.to_json();
86			let json_str = unwrap_json_str_or_invalid(&json);
87			tracing::trace!(target: "jsonrpsee", "response = {}", truncate_at_char_boundary(json_str, max as usize));
88			rp
89		}
90		.in_current_span()
91	}
92
93	#[tracing::instrument(name = "batch", skip_all, fields(method = "batch"), level = "trace")]
94	fn batch<'a>(&self, batch: Batch<'a>) -> impl Future<Output = Self::BatchResponse> + Send + 'a {
95		let json = serde_json::value::to_raw_value(&batch);
96		let json_str = unwrap_json_str_or_invalid(&json);
97		tracing::trace!(target: "jsonrpsee", "batch request = {}", truncate_at_char_boundary(json_str, self.max as usize));
98		let service = self.service.clone();
99		let max = self.max;
100
101		async move {
102			let rp = service.batch(batch).await;
103
104			let json = rp.to_json();
105			let json_str = unwrap_json_str_or_invalid(&json);
106			tracing::trace!(target: "jsonrpsee", "batch response = {}", truncate_at_char_boundary(json_str, max as usize));
107
108			rp
109		}
110		.in_current_span()
111	}
112
113	#[tracing::instrument(name = "notification", skip_all, fields(method = &*n.method), level = "trace")]
114	fn notification<'a>(&self, n: Notification<'a>) -> impl Future<Output = Self::NotificationResponse> + Send + 'a {
115		let json = serde_json::value::to_raw_value(&n);
116		let json_str = unwrap_json_str_or_invalid(&json);
117		tracing::trace!(target: "jsonrpsee", "notification request = {}", truncate_at_char_boundary(json_str, self.max as usize));
118
119		self.service.notification(n).in_current_span()
120	}
121}
122
123fn unwrap_json_str_or_invalid(json: &Result<Box<RawValue>, serde_json::Error>) -> &str {
124	match json {
125		Ok(s) => s.get(),
126		Err(_) => "<invalid JSON>",
127	}
128}
129
130/// Find the next char boundary to truncate at.
131fn truncate_at_char_boundary(s: &str, max: usize) -> &str {
132	if s.len() < max {
133		return s;
134	}
135
136	match s.char_indices().nth(max) {
137		None => s,
138		Some((idx, _)) => &s[..idx],
139	}
140}
141
142#[cfg(test)]
143mod tests {
144	use super::truncate_at_char_boundary;
145
146	#[test]
147	fn truncate_at_char_boundary_works() {
148		assert_eq!(truncate_at_char_boundary("ボルテックス", 0), "");
149		assert_eq!(truncate_at_char_boundary("ボルテックス", 4), "ボルテッ");
150		assert_eq!(truncate_at_char_boundary("ボルテックス", 100), "ボルテックス");
151		assert_eq!(truncate_at_char_boundary("hola-hola", 4), "hola");
152	}
153}