Skip to content

Commit

Permalink
add tide-log
Browse files Browse the repository at this point in the history
  • Loading branch information
prasannavl committed May 20, 2019
1 parent 85b85e9 commit e7a7dac
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[workspace]
members = [
"tide",
"tide-log",
"tide-compression",
"tide-cookies",
"tide-core",
Expand Down
24 changes: 24 additions & 0 deletions tide-log/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
authors = [
"Tide Developers"
]
description = "Tide middleware for logging"
documentation = "https://docs.rs/tide-log"
keywords = ["tide", "web", "async", "middleware", "logging"]
categories = [
"logging",
"network-programming",
"web-programming::http-server",
]
edition = "2018"
license = "MIT OR Apache-2.0"
name = "tide-log"
readme = "README.md"
repository = "https://github.com/rustasync/tide"
version = "0.1.0"

[dependencies]
tide = { path = "../tide" }
futures-preview = "0.3.0-alpha.16"
http = "0.1"
log = "0.4.6"
65 changes: 65 additions & 0 deletions tide-log/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#![feature(async_await)]
#![deny(
nonstandard_style,
rust_2018_idioms,
future_incompatible,
missing_debug_implementations
)]

use futures::future::BoxFuture;
use log::{info, trace};
use tide::{
middleware::{Middleware, Next},
Context, Response,
};

macro_rules! box_async {
{$($t:tt)*} => {
::futures::future::FutureExt::boxed(async move { $($t)* })
};
}

/// A simple requests logger
///
/// # Examples
///
/// ```rust
///
/// let mut app = tide::App::new();
/// app.middleware(tide_log::RequestLogger::new());
/// ```
#[derive(Debug, Clone, Default)]
pub struct RequestLogger;

impl RequestLogger {
pub fn new() -> Self {
Self::default()
}

async fn log_basic<'a, Data: Send + Sync + 'static>(
&'a self,
ctx: Context<Data>,
next: Next<'a, Data>,
) -> tide::Response {
let path = ctx.uri().path().to_owned();
let method = ctx.method().as_str().to_owned();
trace!("IN => {} {}", method, path);
let start = std::time::Instant::now();
let res = next.run(ctx).await;
let status = res.status();
info!(
"{} {} {} {}ms",
method,
path,
status.as_str(),
start.elapsed().as_millis()
);
res
}
}

impl<Data: Send + Sync + 'static> Middleware<Data> for RequestLogger {
fn handle<'a>(&'a self, ctx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
box_async! { self.log_basic(ctx, next).await }
}
}

0 comments on commit e7a7dac

Please sign in to comment.