1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#![deny(missing_docs, warnings)]

//! Request logging middleware for Iron

extern crate iron;
extern crate time;
extern crate term;

use iron::{AfterMiddleware, BeforeMiddleware, IronResult, IronError, Request, Response, status};
use iron::typemap::Key;
use term::{StdoutTerminal, stdout};

use std::io;
use std::error::Error;
use std::fmt::{self, Display, Formatter};

use format::FormatText::{Str, Method, URI, Status, ResponseTime};
use format::FormatColor::{ConstantColor, FunctionColor};
use format::FormatAttr::{ConstantAttrs, FunctionAttrs};
use format::{Format, FormatText};

pub mod format;

/// `Middleware` for logging request and response info to the terminal.
pub struct Logger {
    format: Option<Format>
}

impl Logger {
    /// Create a pair of `Logger` middlewares with the specified `format`. If a `None` is passed in, uses the default format:
    ///
    /// ```ignore
    /// {method} {uri} -> {status} ({response_time} ms)
    /// ```
    ///
    /// While the returned value can be passed straight to `Chain::link`, consider making the logger `BeforeMiddleware`
    /// the first in your chain and the logger `AfterMiddleware` the last by doing something like this:
    ///
    /// ```ignore
    /// let mut chain = Chain::new(handler);
    /// let (logger_before, logger_after) = Logger::new(None);
    /// chain.link_before(logger_before);
    /// // link other middlewares here...
    /// chain.link_after(logger_after);
    /// ```
    pub fn new(format: Option<Format>) -> (Logger, Logger) {
        (Logger { format: format.clone() }, Logger { format: format })
    }
}

struct StartTime;
impl Key for StartTime { type Value = u64; }

impl Logger {
    fn initialise(&self, req: &mut Request) {
        req.extensions.insert::<StartTime>(time::precise_time_ns());
    }

    fn log(&self, req: &mut Request, res: &Response) -> IronResult<()> {
        let exit_time = time::precise_time_ns();
        let entry_time = *req.extensions.get::<StartTime>().unwrap();

        let response_time_ms = (exit_time - entry_time) as f64 / 1000000.0;
        let Format(format) = self.format.clone().unwrap_or_default();

        {
            let render = |text: &FormatText| {
                match *text {
                    Str(ref string) => string.clone(),
                    Method => format!("{}", req.method),
                    URI => format!("{}", req.url),
                    Status => format!("{}", res.status.unwrap()),
                    ResponseTime => format!("{} ms", response_time_ms)
                }
            };

            let log = |mut t: Box<StdoutTerminal>| -> io::Result<()> {
                for unit in format.iter() {
                    match unit.color {
                        ConstantColor(Some(color)) => { try!(t.fg(color)); }
                        ConstantColor(None) => (),
                        FunctionColor(f) => match f(req, res) {
                            Some(color) => { try!(t.fg(color)); }
                            None => ()
                        }
                    }
                    match unit.attrs {
                        ConstantAttrs(ref attrs) => {
                            for &attr in attrs.iter() {
                                try!(t.attr(attr));
                            }
                        }
                        FunctionAttrs(f) => {
                            for &attr in f(req, res).iter() {
                                try!(t.attr(attr));
                            }
                        }
                    }
                    try!(write!(t, "{}", render(&unit.text)));
                    try!(t.reset());
                }
                try!(writeln!(t, ""));
                Ok(())
            };

            match stdout() {
                Some(terminal) => {
                    match log(terminal) {
                        Ok(result) => result,
                        Err(err) => return Err(IronError::new(err, status::InternalServerError))
                    }
                }
                None => { return Err(IronError::new(CouldNotOpenTerminal,
                                                    status::InternalServerError)) }
            };
        }

        Ok(())
    }
}

impl BeforeMiddleware for Logger {
    fn before(&self, req: &mut Request) -> IronResult<()> {
        self.initialise(req);
        Ok(())
    }

    fn catch(&self, req: &mut Request, err: IronError) -> IronResult<()> {
        self.initialise(req);
        Err(err)
    }
}

impl AfterMiddleware for Logger {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
        try!(self.log(req, &res));
        Ok(res)
    }

    fn catch(&self, req: &mut Request, err: IronError) -> IronResult<Response> {
        try!(self.log(req, &err.response));
        Err(err)
    }
}

/// Error returned when logger cannout access stdout.
#[derive(Debug, Clone, Copy)]
pub struct CouldNotOpenTerminal;

impl Error for CouldNotOpenTerminal {
    fn description(&self) -> &str {
        "Could Not Open Terminal"
    }
}

impl Display for CouldNotOpenTerminal {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Logger could not open stdout as a terminal.")
    }
}