Skip to content
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

Stop allocating so much while formatting. #100

Merged
merged 5 commits into from
Jan 15, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/formatstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ extern crate env_logger;
use iron::prelude::*;

use logger::Logger;
use logger::format::Format;
use logger::Format;

static FORMAT: &'static str =
"Uri: {uri}, Method: {method}, Status: {status}, Duration: {response-time}, Time: {request-time}";
Expand All @@ -19,7 +19,7 @@ fn main() {
let mut chain = Chain::new(no_op_handler);
let format = Format::new(FORMAT);
chain.link(Logger::new(Some(format.unwrap())));

println!("Run `RUST_LOG=info cargo run --example formatstring` to see logs.");
match Iron::new(chain).http("127.0.0.1:3000") {
Result::Ok(listening) => println!("{:?}", listening),
Expand Down
31 changes: 30 additions & 1 deletion src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
use std::default::Default;
use std::str::Chars;
use std::iter::Peekable;
use std::fmt::Formatter;

use self::FormatText::{Method, URI, Status, ResponseTime, RemoteAddr, RequestTime};

/// A formatting style for the `Logger`, consisting of multiple
/// `FormatUnit`s concatenated into one line.
#[derive(Clone)]
pub struct Format(pub Vec<FormatUnit>);
pub struct Format(Vec<FormatUnit>);

impl Default for Format {
/// Return the default formatting style for the `Logger`:
Expand Down Expand Up @@ -44,6 +45,16 @@ impl Format {

Some(Format(results))
}

}

pub fn display_with<'a>(format: &'a Format,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally this would be a method on Format, but I realize that this is not possible due to the wish to constrain the public API.

You could also think about it as a constructor of FormatDisplay but I'm not sure if that's an internal API we want.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I turned it into a method of a private trait. I'm not entirely sure that the trait is appropriately generic, but given that it currently has a single use, I don't think that is a big deal.

render: &'a Fn(&mut Formatter, &FormatText) -> Result<(), fmt::Error>)
-> FormatDisplay<'a> {
FormatDisplay {
format: format,
render: render,
}
}

struct FormatParser<'a> {
Expand Down Expand Up @@ -173,3 +184,21 @@ pub enum FormatText {
pub struct FormatUnit {
pub text: FormatText,
}


#[doc(hidden)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not necessary if the entire mod is not public, no?

pub struct FormatDisplay<'a> {
format: &'a Format,
render: &'a Fn(&mut Formatter, &FormatText) -> Result<(), fmt::Error>,
}

use std::fmt;
impl<'a> fmt::Display for FormatDisplay<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
let Format(ref format) = *self.format;
for unit in format {
(self.render)(fmt, &unit.text)?;
}
Ok(())
}
}
39 changes: 23 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ use iron::{AfterMiddleware, BeforeMiddleware, IronResult, IronError, Request, Re
use iron::typemap::Key;

use format::FormatText::{Str, Method, URI, Status, ResponseTime, RemoteAddr, RequestTime};
use format::{Format, FormatText};
use format::{FormatText};

pub mod format;
use std::fmt::Formatter;

mod format;
pub use format::Format;

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

impl Logger {
Expand All @@ -37,6 +40,7 @@ impl Logger {
/// chain.link_after(logger_after);
/// ```
pub fn new(format: Option<Format>) -> (Logger, Logger) {
let format = format.unwrap_or_default();
(Logger { format: format.clone() }, Logger { format: format })
}
}
Expand All @@ -54,25 +58,28 @@ impl Logger {

let response_time = time::now() - entry_time;
let response_time_ms = (response_time.num_seconds() * 1000) as f64 + (response_time.num_nanoseconds().unwrap_or(0) as f64) / 1000000.0;
let Format(format) = self.format.clone().unwrap_or_default();

{
let render = |text: &FormatText| {
let render = |fmt: &mut Formatter, text: &FormatText| {
match *text {
Str(ref string) => string.clone(),
Method => format!("{}", req.method),
URI => format!("{}", req.url),
Status => res.status
.map(|status| format!("{}", status))
.unwrap_or("<missing status code>".to_owned()),
ResponseTime => format!("{} ms", response_time_ms),
RemoteAddr => format!("{}", req.remote_addr),
RequestTime => format!("{}", entry_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ%z").unwrap()),
Str(ref string) => fmt.write_str(string),
Method => fmt.write_fmt(format_args!("{}", req.method)),
URI => fmt.write_fmt(format_args!("{}", req.url)),
Status => match res.status {
Some(status) => fmt.write_fmt(format_args!("{}", status)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can replace this with status.fmt I think. Same goes for similar branches.

None => fmt.write_str("<missing status code>"),
},
ResponseTime => fmt.write_fmt(format_args!("{} ms", response_time_ms)),
RemoteAddr => fmt.write_fmt(format_args!("{}", req.remote_addr)),
RequestTime => {
fmt.write_fmt(format_args!("{}",
entry_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ%z")
.unwrap()))
},
}
};

let lg = format.iter().map(|unit| render(&unit.text)).collect::<Vec<String>>().join("");
info!("{}", lg);
info!("{}", format::display_with(&self.format, &render));
}

Ok(())
Expand Down