Skip to content

Commit 48f4056

Browse files
committed
add support for custom log metadata
1 parent d9ab811 commit 48f4056

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

src/controllers.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ mod prelude {
3838
fn query(&self) -> IndexMap<String, String>;
3939
fn wants_json(&self) -> bool;
4040
fn query_with_params(&self, params: IndexMap<String, String>) -> String;
41+
42+
fn log_metadata<V: std::fmt::Display>(&mut self, key: &'static str, value: V);
4143
}
4244

4345
impl<'a> RequestUtils for dyn Request + 'a {
@@ -76,6 +78,10 @@ mod prelude {
7678
.finish();
7779
format!("?{}", query_string)
7880
}
81+
82+
fn log_metadata<V: std::fmt::Display>(&mut self, key: &'static str, value: V) {
83+
crate::middleware::log_request::add_custom_metadata(self, key, value);
84+
}
7985
}
8086
}
8187

src/middleware.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ mod ember_index_rewrite;
2525
mod ensure_well_formed_500;
2626
mod head;
2727
mod log_connection_pool_status;
28-
mod log_request;
28+
pub mod log_request;
2929
mod require_user_agent;
3030
mod static_or_continue;
3131

src/middleware/log_request.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ impl Handler for LogRequests {
4242
}
4343
}
4444

45+
struct CustomMetadata {
46+
entries: Vec<(&'static str, String)>,
47+
}
48+
49+
pub fn add_custom_metadata<V: Display>(req: &mut dyn Request, key: &'static str, value: V) {
50+
if let Some(metadata) = req.mut_extensions().find_mut::<CustomMetadata>() {
51+
metadata.entries.push((key, value.to_string()));
52+
} else {
53+
let mut metadata = CustomMetadata {
54+
entries: Vec::new(),
55+
};
56+
metadata.entries.push((key, value.to_string()));
57+
req.mut_extensions().insert(metadata);
58+
}
59+
}
60+
4561
struct RequestLine<'r> {
4662
req: &'r dyn Request,
4763
res: &'r Result<Response>,
@@ -66,6 +82,12 @@ impl Display for RequestLine<'_> {
6682
line.add_field("status", status)?;
6783
line.add_quoted_field("user_agent", request_header(self.req, "User-Agent"))?;
6884

85+
if let Some(metadata) = self.req.extensions().find::<CustomMetadata>() {
86+
for (key, value) in &metadata.entries {
87+
line.add_quoted_field(key, value)?;
88+
}
89+
}
90+
6991
if let Some(len) = self.req.extensions().find::<u64>() {
7092
line.add_field("metadata_length", len)?;
7193
}

0 commit comments

Comments
 (0)