1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00

add Logger::log_target (#2594)

This commit is contained in:
Rob Ede 2022-01-21 17:18:39 +00:00
parent ae7f71e317
commit cb7347216c
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
3 changed files with 43 additions and 6 deletions

View File

@ -2,7 +2,8 @@
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
### Added ### Added
- `HttpResponse::add_removal_cookie` [#2586] - `HttpResponse::add_removal_cookie`. [#2586]
- `Logger::log_target`. [#2594]
### Removed ### Removed
- `HttpRequest::req_data[_mut]()`; request-local data is still available through `.extensions()`. [#2585] - `HttpRequest::req_data[_mut]()`; request-local data is still available through `.extensions()`. [#2585]
@ -11,6 +12,7 @@
[#2585]: https://github.com/actix/actix-web/pull/2585 [#2585]: https://github.com/actix/actix-web/pull/2585
[#2586]: https://github.com/actix/actix-web/pull/2586 [#2586]: https://github.com/actix/actix-web/pull/2586
[#2591]: https://github.com/actix/actix-web/pull/2591 [#2591]: https://github.com/actix/actix-web/pull/2591
[#2594]: https://github.com/actix/actix-web/pull/2594
## 4.0.0-beta.20 - 2022-01-14 ## 4.0.0-beta.20 - 2022-01-14

View File

@ -24,7 +24,7 @@ async fn main() -> std::io::Result<()> {
App::new() App::new()
.wrap(middleware::DefaultHeaders::new().add(("X-Version", "0.2"))) .wrap(middleware::DefaultHeaders::new().add(("X-Version", "0.2")))
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.wrap(middleware::Logger::default().log_target("1234")) .wrap(middleware::Logger::default().log_target("http_log"))
.service(index) .service(index)
.service(no_params) .service(no_params)
.service( .service(

View File

@ -1,6 +1,7 @@
//! For middleware documentation, see [`Logger`]. //! For middleware documentation, see [`Logger`].
use std::{ use std::{
borrow::Cow,
collections::HashSet, collections::HashSet,
convert::TryFrom, convert::TryFrom,
env, env,
@ -87,6 +88,7 @@ struct Inner {
format: Format, format: Format,
exclude: HashSet<String>, exclude: HashSet<String>,
exclude_regex: RegexSet, exclude_regex: RegexSet,
log_target: Cow<'static, str>,
} }
impl Logger { impl Logger {
@ -96,6 +98,7 @@ impl Logger {
format: Format::new(format), format: Format::new(format),
exclude: HashSet::new(), exclude: HashSet::new(),
exclude_regex: RegexSet::empty(), exclude_regex: RegexSet::empty(),
log_target: Cow::Borrowed(module_path!()),
})) }))
} }
@ -118,6 +121,24 @@ impl Logger {
self self
} }
/// Sets the logging target to `target`.
///
/// By default, the log target is `module_path!()` of the log call location. In our case, that
/// would be `actix_web::middleware::logger`.
///
/// # Examples
/// Using `.log_target("http_log")` would have this effect on request logs:
/// ```diff
/// - [2015-10-21T07:28:00Z INFO actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
/// + [2015-10-21T07:28:00Z INFO http_log] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985
/// ^^^^^^^^
/// ```
pub fn log_target(mut self, target: impl Into<Cow<'static, str>>) -> Self {
let inner = Rc::get_mut(&mut self.0).unwrap();
inner.log_target = target.into();
self
}
/// Register a function that receives a ServiceRequest and returns a String for use in the /// Register a function that receives a ServiceRequest and returns a String for use in the
/// log line. The label passed as the first argument should match a replacement substring in /// log line. The label passed as the first argument should match a replacement substring in
/// the logger format like `%{label}xi`. /// the logger format like `%{label}xi`.
@ -171,6 +192,7 @@ impl Default for Logger {
format: Format::default(), format: Format::default(),
exclude: HashSet::new(), exclude: HashSet::new(),
exclude_regex: RegexSet::empty(), exclude_regex: RegexSet::empty(),
log_target: Cow::Borrowed(module_path!()),
})) }))
} }
} }
@ -222,13 +244,15 @@ where
actix_service::forward_ready!(service); actix_service::forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future { fn call(&self, req: ServiceRequest) -> Self::Future {
if self.inner.exclude.contains(req.path()) let excluded = self.inner.exclude.contains(req.path())
|| self.inner.exclude_regex.is_match(req.path()) || self.inner.exclude_regex.is_match(req.path());
{
if excluded {
LoggerResponse { LoggerResponse {
fut: self.service.call(req), fut: self.service.call(req),
format: None, format: None,
time: OffsetDateTime::now_utc(), time: OffsetDateTime::now_utc(),
log_target: Cow::Borrowed(""),
_phantom: PhantomData, _phantom: PhantomData,
} }
} else { } else {
@ -238,10 +262,12 @@ where
for unit in &mut format.0 { for unit in &mut format.0 {
unit.render_request(now, &req); unit.render_request(now, &req);
} }
LoggerResponse { LoggerResponse {
fut: self.service.call(req), fut: self.service.call(req),
format: Some(format), format: Some(format),
time: now, time: now,
log_target: self.inner.log_target.clone(),
_phantom: PhantomData, _phantom: PhantomData,
} }
} }
@ -258,6 +284,7 @@ pin_project! {
fut: S::Future, fut: S::Future,
time: OffsetDateTime, time: OffsetDateTime,
format: Option<Format>, format: Option<Format>,
log_target: Cow<'static, str>,
_phantom: PhantomData<B>, _phantom: PhantomData<B>,
} }
} }
@ -289,12 +316,14 @@ where
let time = *this.time; let time = *this.time;
let format = this.format.take(); let format = this.format.take();
let log_target = this.log_target.clone();
Poll::Ready(Ok(res.map_body(move |_, body| StreamLog { Poll::Ready(Ok(res.map_body(move |_, body| StreamLog {
body, body,
time, time,
format, format,
size: 0, size: 0,
log_target,
}))) })))
} }
} }
@ -306,7 +335,9 @@ pin_project! {
format: Option<Format>, format: Option<Format>,
size: usize, size: usize,
time: OffsetDateTime, time: OffsetDateTime,
log_target: Cow<'static, str>,
} }
impl<B> PinnedDrop for StreamLog<B> { impl<B> PinnedDrop for StreamLog<B> {
fn drop(this: Pin<&mut Self>) { fn drop(this: Pin<&mut Self>) {
if let Some(ref format) = this.format { if let Some(ref format) = this.format {
@ -316,7 +347,11 @@ pin_project! {
} }
Ok(()) Ok(())
}; };
log::info!("{}", FormatDisplay(&render));
log::info!(
target: this.log_target.as_ref(),
"{}", FormatDisplay(&render)
);
} }
} }
} }