-
Notifications
You must be signed in to change notification settings - Fork 37
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
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f6bd6ae
Stop allocating so much while formatting.
tomprince 8c4e50b
Cleanup public API.
tomprince bdcd4c5
Call `Display::fmt` directly, rather than using `format_args!`.
tomprince e6dd87d
Get rid of unneeded `#[doc(hidden)]`.
tomprince c9401eb
Make display_with a trait method.
tomprince File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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`: | ||
|
@@ -44,6 +45,16 @@ impl Format { | |
|
||
Some(Format(results)) | ||
} | ||
|
||
} | ||
|
||
pub fn display_with<'a>(format: &'a Format, | ||
render: &'a Fn(&mut Formatter, &FormatText) -> Result<(), fmt::Error>) | ||
-> FormatDisplay<'a> { | ||
FormatDisplay { | ||
format: format, | ||
render: render, | ||
} | ||
} | ||
|
||
struct FormatParser<'a> { | ||
|
@@ -173,3 +184,21 @@ pub enum FormatText { | |
pub struct FormatUnit { | ||
pub text: FormatText, | ||
} | ||
|
||
|
||
#[doc(hidden)] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 { | ||
|
@@ -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 }) | ||
} | ||
} | ||
|
@@ -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)), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can replace this with |
||
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(()) | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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.