Add %R (Route) for logger

This commit is contained in:
Haze Booth 2019-04-02 14:14:17 -04:00
parent c27fbdc35f
commit 56d0f6607b
1 changed files with 40 additions and 1 deletions

View File

@ -65,6 +65,8 @@ use crate::{HttpMessage, HttpResponse};
/// ///
/// `%D` Time taken to serve the request, in milliseconds /// `%D` Time taken to serve the request, in milliseconds
/// ///
/// `%R` Request route
///
/// `%{FOO}i` request.headers['FOO'] /// `%{FOO}i` request.headers['FOO']
/// ///
/// `%{FOO}o` response.headers['FOO'] /// `%{FOO}o` response.headers['FOO']
@ -272,7 +274,7 @@ impl Format {
/// Returns `None` if the format string syntax is incorrect. /// Returns `None` if the format string syntax is incorrect.
pub fn new(s: &str) -> Format { pub fn new(s: &str) -> Format {
log::trace!("Access log format: {}", s); log::trace!("Access log format: {}", s);
let fmt = Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrsbTD]?)").unwrap(); let fmt = Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrRsbTD]?)").unwrap();
let mut idx = 0; let mut idx = 0;
let mut results = Vec::new(); let mut results = Vec::new();
@ -300,6 +302,7 @@ impl Format {
"r" => FormatText::RequestLine, "r" => FormatText::RequestLine,
"s" => FormatText::ResponseStatus, "s" => FormatText::ResponseStatus,
"b" => FormatText::ResponseSize, "b" => FormatText::ResponseSize,
"R" => FormatText::Route,
"T" => FormatText::Time, "T" => FormatText::Time,
"D" => FormatText::TimeMillis, "D" => FormatText::TimeMillis,
_ => FormatText::Str(m.as_str().to_owned()), _ => FormatText::Str(m.as_str().to_owned()),
@ -328,6 +331,7 @@ pub enum FormatText {
Time, Time,
TimeMillis, TimeMillis,
RemoteAddr, RemoteAddr,
Route,
RequestHeader(String), RequestHeader(String),
ResponseHeader(String), ResponseHeader(String),
EnvironHeader(String), EnvironHeader(String),
@ -413,6 +417,12 @@ impl FormatText {
)) ))
}; };
} }
FormatText::Route => {
*self = FormatText::Str(format!(
"{}",
req.path()
))
}
FormatText::RequestTime => { FormatText::RequestTime => {
*self = FormatText::Str(format!( *self = FormatText::Str(format!(
"{:?}", "{:?}",
@ -473,6 +483,35 @@ mod tests {
let _res = block_on(srv.call(req)); let _res = block_on(srv.call(req));
} }
#[test]
fn test_route() {
let mut format = Format::new("%T %R");
let req = TestRequest::with_header(
header::USER_AGENT,
header::HeaderValue::from_static("ACTIX-WEB"),
).uri("/test/route/yeah").to_srv_request();
let now = time::now();
for unit in &mut format.0 {
unit.render_request(now, &req);
}
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
for unit in &mut format.0 {
unit.render_response(&resp);
}
let render = |fmt: &mut Formatter| {
for unit in &format.0 {
unit.render(fmt, 1024, now)?;
}
Ok(())
};
let s = format!("{}", FormatDisplay(&render));
println!("{}", s);
assert!(s.contains("/test/route/yeah"));
}
#[test] #[test]
fn test_default_format() { fn test_default_format() {
let mut format = Format::default(); let mut format = Format::default();