Skip to content

Commit 4df808d

Browse files
prasannavlfairingrey
authored andcommitted
add tide-log (#222)
* add tide-log * remove box_async macro
1 parent 5ec263e commit 4df808d

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ members = [
5858
"tide-compression",
5959
"tide-cookies",
6060
"tide-core",
61+
"tide-log",
6162
]
6263

6364
[patch.crates-io]

tide-log/Cargo.toml

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
[package]
2+
authors = [
3+
"Tide Developers"
4+
]
5+
description = "Tide middleware for logging"
6+
documentation = "https://docs.rs/tide-log"
7+
keywords = ["tide", "web", "async", "middleware", "logging"]
8+
categories = [
9+
"logging",
10+
"network-programming",
11+
"web-programming::http-server",
12+
]
13+
edition = "2018"
14+
license = "MIT OR Apache-2.0"
15+
name = "tide-log"
16+
readme = "README.md"
17+
repository = "https://github.com/rustasync/tide"
18+
version = "0.1.0"
19+
20+
[dependencies]
21+
tide = { path = "../" }
22+
futures-preview = "0.3.0-alpha.16"
23+
http = "0.1"
24+
log = "0.4.6"

tide-log/src/lib.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#![feature(async_await)]
2+
#![deny(
3+
nonstandard_style,
4+
rust_2018_idioms,
5+
future_incompatible,
6+
missing_debug_implementations
7+
)]
8+
9+
use futures::future::BoxFuture;
10+
use futures::prelude::*;
11+
use log::{info, trace};
12+
use tide::{
13+
middleware::{Middleware, Next},
14+
Context, Response,
15+
};
16+
17+
/// A simple requests logger
18+
///
19+
/// # Examples
20+
///
21+
/// ```rust
22+
///
23+
/// let mut app = tide::App::new();
24+
/// app.middleware(tide_log::RequestLogger::new());
25+
/// ```
26+
#[derive(Debug, Clone, Default)]
27+
pub struct RequestLogger;
28+
29+
impl RequestLogger {
30+
pub fn new() -> Self {
31+
Self::default()
32+
}
33+
34+
async fn log_basic<'a, Data: Send + Sync + 'static>(
35+
&'a self,
36+
ctx: Context<Data>,
37+
next: Next<'a, Data>,
38+
) -> tide::Response {
39+
let path = ctx.uri().path().to_owned();
40+
let method = ctx.method().as_str().to_owned();
41+
trace!("IN => {} {}", method, path);
42+
let start = std::time::Instant::now();
43+
let res = next.run(ctx).await;
44+
let status = res.status();
45+
info!(
46+
"{} {} {} {}ms",
47+
method,
48+
path,
49+
status.as_str(),
50+
start.elapsed().as_millis()
51+
);
52+
res
53+
}
54+
}
55+
56+
impl<Data: Send + Sync + 'static> Middleware<Data> for RequestLogger {
57+
fn handle<'a>(&'a self, ctx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
58+
FutureExt::boxed(async move { self.log_basic(ctx, next).await })
59+
}
60+
}

0 commit comments

Comments
 (0)