-
Notifications
You must be signed in to change notification settings - Fork 273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Logging middleware #614
Comments
I'm afraid it's not really possible. You could block (see |
Thanks for the help. The performance not a problem, since the package purpose will be logging layer, so that would be the functionality to log these out.
This is my current code, but it's throw me an error:
That's weird because the IDE tells me that it's implementing the HttpBody trait and show me the poll_data function as well. |
@PumpkinSeed we use |
Yes that was the issue. I made some modification, and it's compile now (which should be a good point in Rust), but I got timeout.
The output:
I do really appreciate the help. If I completely figure out I will contribute back with an example details the usage. Maybe it will be a big help in the future. |
So Could you please instead try using Also please double note that this is really not a recommended way of using middlewares, and it will most likely back fire again in the (hopefuly not) near future. |
Will it be better to use #[derive(Debug, Default)]
struct LoggingMiddleware{
}
#[derive(Clone, Debug, Default)]
struct Meta(());
impl Metadata for Meta {}
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,
{
let start = Instant::now();
let req_id = Uuid::new_v4().to_string();
let span = info_span!("jsonrpc",request_id = %req_id);
let _entered = span.entered();
let span1= info_span!("json calling");
log::info!("request: {}",serde_json::to_string_pretty(&request).unwrap_or_default());
Either::Left(Box::pin(next(request, meta).map(move |res| {
if let Some(v) = &res {
log::info!("response:{}", serde_json::to_string_pretty(&v).unwrap_or_default());
}
log::info!("Processing took: {:.6}", start.elapsed().as_micros() as f64/1000_000.0);
res
}).instrument(span1)))
}
} |
@tomusdrw It's my output. hope can help u Processing request Single(MethodCall(MethodCall { jsonrpc: Some(V2), method: "say_hello", params: Array([]), id: Num(123) }))
Processing took: 121.083µs use jsonrpc_http_server::jsonrpc_core::futures_util::{future::Either, FutureExt};
use jsonrpc_http_server::jsonrpc_core::*;
use jsonrpc_http_server::{cors::AccessControlAllowHeaders, hyper, RestApi, ServerBuilder};
use std::future::Future;
use std::sync::atomic::AtomicUsize;
use std::time::Instant;
#[derive(Default, Clone)]
struct Meta {
auth: Option<String>,
}
impl Metadata for Meta {}
#[derive(Default)]
struct LoggerMiddleware(AtomicUsize);
impl Middleware<Meta> for LoggerMiddleware {
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,
{
let start = Instant::now();
println!("Processing request {:?}", request);
Either::Left(Box::pin(next(request, meta).map(move |res| {
println!("Processing took: {:?}", start.elapsed());
res
})))
}
}
fn main() {
env_logger::init();
let mut io = MetaIoHandler::new(Compatibility::Both, LoggerMiddleware::default());
io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
let auth = meta.auth.unwrap_or_else(String::new);
futures::future::ready(if auth.as_str() == "let-me-in" {
Ok(Value::String("Hello World!".to_owned()))
} else {
Ok(Value::String("Access Denied!".to_owned()))
})
});
let server = ServerBuilder::new(io)
.cors_allow_headers(AccessControlAllowHeaders::Only(vec![
"Authorization".to_owned()
]))
.rest_api(RestApi::Unsecure)
// You can also implement `MetaExtractor` trait and pass a struct here.
.meta_extractor(|req: &hyper::Request<hyper::Body>| {
let auth = req
.headers()
.get(hyper::header::AUTHORIZATION)
.map(|h| h.to_str().unwrap_or("").to_owned());
Meta { auth }
})
.start_http(&"127.0.0.1:3030".parse().unwrap())
.expect("Unable to start RPC server");
server.wait();
} |
Firstly thanks for the library. :)
I wanted to implement a logging middleware but I had a problem. There is the actual implementation.
It logged that line:
Is there any way that I can make it visible?
The text was updated successfully, but these errors were encountered: