Skip to content

Commit 4519db3

Browse files
jdeepeerobjtede
andauthored
register fns for custom request-derived logging units (#1749)
Co-authored-by: Rob Ede <[email protected]>
1 parent 7030bf5 commit 4519db3

2 files changed

Lines changed: 142 additions & 16 deletions

File tree

‎CHANGES.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
### Added
55
* Implement `exclude_regex` for Logger middleware. [#1723]
66
* Add request-local data extractor `web::ReqData`. [#1748]
7+
* Add ability to register closure for request middleware logging. [#1749]
78
* Add `app_data` to `ServiceConfig`. [#1757]
89

910
### Changed
@@ -15,6 +16,7 @@
1516
[#1743]: https://github.com/actix/actix-web/pull/1743
1617
[#1748]: https://github.com/actix/actix-web/pull/1748
1718
[#1750]: https://github.com/actix/actix-web/pull/1750
19+
[#1749]: https://github.com/actix/actix-web/pull/1749
1820

1921

2022
## 3.1.0 - 2020-09-29

‎src/middleware/logger.rs‎

Lines changed: 140 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,21 +34,19 @@ use crate::HttpResponse;
3434
/// Default `Logger` could be created with `default` method, it uses the
3535
/// default format:
3636
///
37-
/// ```ignore
38-
/// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
37+
/// ```plain
38+
/// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
3939
/// ```
40+
///
4041
/// ```rust
41-
/// use actix_web::middleware::Logger;
42-
/// use actix_web::App;
42+
/// use actix_web::{middleware::Logger, App};
4343
///
44-
/// fn main() {
45-
/// std::env::set_var("RUST_LOG", "actix_web=info");
46-
/// env_logger::init();
44+
/// std::env::set_var("RUST_LOG", "actix_web=info");
45+
/// env_logger::init();
4746
///
48-
/// let app = App::new()
49-
/// .wrap(Logger::default())
50-
/// .wrap(Logger::new("%a %{User-Agent}i"));
51-
/// }
47+
/// let app = App::new()
48+
/// .wrap(Logger::default())
49+
/// .wrap(Logger::new("%a %{User-Agent}i"));
5250
/// ```
5351
///
5452
/// ## Format
@@ -80,6 +78,8 @@ use crate::HttpResponse;
8078
///
8179
/// `%{FOO}e` os.environ['FOO']
8280
///
81+
/// `%{FOO}xi` [custom request replacement](Logger::custom_request_replace) labelled "FOO"
82+
///
8383
/// # Security
8484
/// **\*** It is calculated using
8585
/// [`ConnectionInfo::realip_remote_addr()`](../dev/struct.ConnectionInfo.html#method.realip_remote_addr)
@@ -123,12 +123,52 @@ impl Logger {
123123
inner.exclude_regex = regex_set;
124124
self
125125
}
126+
127+
/// Register a function that receives a ServiceRequest and returns a String for use in the
128+
/// log line. The label passed as the first argument should match a replacement substring in
129+
/// the logger format like `%{label}xi`.
130+
///
131+
/// It is convention to print "-" to indicate no output instead of an empty string.
132+
///
133+
/// # Example
134+
/// ```rust
135+
/// # use actix_web::{http::HeaderValue, middleware::Logger};
136+
/// # fn parse_jwt_id (_req: Option<&HeaderValue>) -> String { "jwt_uid".to_owned() }
137+
/// Logger::new("example %{JWT_ID}xi")
138+
/// .custom_request_replace("JWT_ID", |req| parse_jwt_id(req.headers().get("Authorization")));
139+
/// ```
140+
pub fn custom_request_replace(
141+
mut self,
142+
label: &str,
143+
f: impl Fn(&ServiceRequest) -> String + 'static,
144+
) -> Self {
145+
let inner = Rc::get_mut(&mut self.0).unwrap();
146+
147+
let ft = inner.format.0.iter_mut().find(|ft| {
148+
matches!(ft, FormatText::CustomRequest(unit_label, _) if label == unit_label)
149+
});
150+
151+
if let Some(FormatText::CustomRequest(_, request_fn)) = ft {
152+
// replace into None or previously registered fn using same label
153+
request_fn.replace(CustomRequestFn {
154+
inner_fn: Rc::new(f),
155+
});
156+
} else {
157+
// non-printed request replacement function diagnostic
158+
debug!(
159+
"Attempted to register custom request logging function for nonexistent label: {}",
160+
label
161+
);
162+
}
163+
164+
self
165+
}
126166
}
127167

128168
impl Default for Logger {
129169
/// Create `Logger` middleware with format:
130170
///
131-
/// ```ignore
171+
/// ```plain
132172
/// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
133173
/// ```
134174
fn default() -> Logger {
@@ -153,6 +193,17 @@ where
153193
type Future = Ready<Result<Self::Transform, Self::InitError>>;
154194

155195
fn new_transform(&self, service: S) -> Self::Future {
196+
for unit in &self.0.format.0 {
197+
// missing request replacement function diagnostic
198+
if let FormatText::CustomRequest(label, None) = unit {
199+
debug!(
200+
"No custom request replacement function was registered for label {} in\
201+
logger format.",
202+
label
203+
);
204+
}
205+
}
206+
156207
ok(LoggerMiddleware {
157208
service,
158209
inner: self.0.clone(),
@@ -311,7 +362,6 @@ impl<B: MessageBody> MessageBody for StreamLog<B> {
311362
/// A formatting style for the `Logger`, consisting of multiple
312363
/// `FormatText`s concatenated into one line.
313364
#[derive(Clone)]
314-
#[doc(hidden)]
315365
struct Format(Vec<FormatText>);
316366

317367
impl Default for Format {
@@ -327,7 +377,8 @@ impl Format {
327377
/// Returns `None` if the format string syntax is incorrect.
328378
pub fn new(s: &str) -> Format {
329379
log::trace!("Access log format: {}", s);
330-
let fmt = Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([aioe])|[atPrUsbTD]?)").unwrap();
380+
let fmt =
381+
Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([aioe]|xi)|[atPrUsbTD]?)").unwrap();
331382

332383
let mut idx = 0;
333384
let mut results = Vec::new();
@@ -355,6 +406,7 @@ impl Format {
355406
HeaderName::try_from(key.as_str()).unwrap(),
356407
),
357408
"e" => FormatText::EnvironHeader(key.as_str().to_owned()),
409+
"xi" => FormatText::CustomRequest(key.as_str().to_owned(), None),
358410
_ => unreachable!(),
359411
})
360412
} else {
@@ -384,7 +436,9 @@ impl Format {
384436
/// A string of text to be logged. This is either one of the data
385437
/// fields supported by the `Logger`, or a custom `String`.
386438
#[doc(hidden)]
439+
#[non_exhaustive]
387440
#[derive(Debug, Clone)]
441+
// TODO: remove pub on next breaking change
388442
pub enum FormatText {
389443
Str(String),
390444
Percent,
@@ -400,6 +454,26 @@ pub enum FormatText {
400454
RequestHeader(HeaderName),
401455
ResponseHeader(HeaderName),
402456
EnvironHeader(String),
457+
CustomRequest(String, Option<CustomRequestFn>),
458+
}
459+
460+
// TODO: remove pub on next breaking change
461+
#[doc(hidden)]
462+
#[derive(Clone)]
463+
pub struct CustomRequestFn {
464+
inner_fn: Rc<dyn Fn(&ServiceRequest) -> String>,
465+
}
466+
467+
impl CustomRequestFn {
468+
fn call(&self, req: &ServiceRequest) -> String {
469+
(self.inner_fn)(req)
470+
}
471+
}
472+
473+
impl fmt::Debug for CustomRequestFn {
474+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475+
f.write_str("custom_request_fn")
476+
}
403477
}
404478

405479
impl FormatText {
@@ -456,7 +530,7 @@ impl FormatText {
456530
}
457531

458532
fn render_request(&mut self, now: OffsetDateTime, req: &ServiceRequest) {
459-
match *self {
533+
match &*self {
460534
FormatText::RequestLine => {
461535
*self = if req.query_string().is_empty() {
462536
FormatText::Str(format!(
@@ -508,11 +582,20 @@ impl FormatText {
508582
};
509583
*self = s;
510584
}
585+
FormatText::CustomRequest(_, request_fn) => {
586+
let s = match request_fn {
587+
Some(f) => FormatText::Str(f.call(req)),
588+
None => FormatText::Str("-".to_owned()),
589+
};
590+
591+
*self = s;
592+
}
511593
_ => (),
512594
}
513595
}
514596
}
515597

598+
/// Converter to get a String from something that writes to a Formatter.
516599
pub(crate) struct FormatDisplay<'a>(
517600
&'a dyn Fn(&mut Formatter<'_>) -> Result<(), fmt::Error>,
518601
);
@@ -530,7 +613,7 @@ mod tests {
530613

531614
use super::*;
532615
use crate::http::{header, StatusCode};
533-
use crate::test::TestRequest;
616+
use crate::test::{self, TestRequest};
534617

535618
#[actix_rt::test]
536619
async fn test_logger() {
@@ -699,4 +782,45 @@ mod tests {
699782
println!("{}", s);
700783
assert!(s.contains("192.0.2.60"));
701784
}
785+
786+
#[actix_rt::test]
787+
async fn test_custom_closure_log() {
788+
let mut logger = Logger::new("test %{CUSTOM}xi")
789+
.custom_request_replace("CUSTOM", |_req: &ServiceRequest| -> String {
790+
String::from("custom_log")
791+
});
792+
let mut unit = Rc::get_mut(&mut logger.0).unwrap().format.0[1].clone();
793+
794+
let label = match &unit {
795+
FormatText::CustomRequest(label, _) => label,
796+
ft => panic!("expected CustomRequest, found {:?}", ft),
797+
};
798+
799+
assert_eq!(label, "CUSTOM");
800+
801+
let req = TestRequest::default().to_srv_request();
802+
let now = OffsetDateTime::now_utc();
803+
804+
unit.render_request(now, &req);
805+
806+
let render = |fmt: &mut Formatter<'_>| unit.render(fmt, 1024, now);
807+
808+
let log_output = FormatDisplay(&render).to_string();
809+
assert_eq!(log_output, "custom_log");
810+
}
811+
812+
#[actix_rt::test]
813+
async fn test_closure_logger_in_middleware() {
814+
let captured = "custom log replacement";
815+
816+
let logger = Logger::new("%{CUSTOM}xi")
817+
.custom_request_replace("CUSTOM", move |_req: &ServiceRequest| -> String {
818+
captured.to_owned()
819+
});
820+
821+
let mut srv = logger.new_transform(test::ok_service()).await.unwrap();
822+
823+
let req = TestRequest::default().to_srv_request();
824+
srv.call(req).await.unwrap();
825+
}
702826
}

0 commit comments

Comments
 (0)