Skip to main content

rust_web_server/log/
mod.rs

1use std::net::SocketAddr;
2use std::thread;
3use crate::entry_point::command_line_args::CommandLineArgument;
4use crate::request::Request;
5use crate::response::Response;
6
7#[cfg(test)]
8mod tests;
9pub(crate) mod access_sink;
10pub mod tail;
11
12/// Logging helpers for access logs and server info.
13///
14/// [`Log::combined`] produces standard Combined Log Format lines compatible with
15/// GoAccess, AWStats, and similar tools. All three server code paths (HTTP/1.1,
16/// HTTP/2, HTTP/3) use it.
17pub struct Log;
18
19impl Log {
20    pub fn request_response(request: &Request, response: &Response, peer_addr: &SocketAddr) -> String {
21        let mut request_headers = "".to_string();
22        for header in &request.headers {
23            if &header.name.chars().count() > &0 {
24                request_headers = [
25                    request_headers,
26                    "\n  ".to_string(),
27                    header.name.to_string(),
28                    ": ".to_string(),
29                    header.value.to_string()
30                ].join("");
31            }
32        }
33
34        let mut response_headers = "".to_string();
35        for header in &response.headers {
36            if &header.name.chars().count() > &0 {
37                response_headers = [
38                    response_headers,
39                    "\n  ".to_string(),
40                    header.name.to_string(),
41                    ": ".to_string(),
42                    header.value.to_string()
43                ].join("");
44            }
45        }
46
47        let mut response_body_length = 0;
48        let mut response_body_parts_number = 0;
49        for content_range in &response.content_range_list {
50            let boxed_parse = content_range.size.parse::<i32>();
51            if boxed_parse.is_ok() {
52                response_body_length += boxed_parse.unwrap();
53                response_body_parts_number += 1;
54            }
55        }
56
57        let current_thread = thread::current();
58        let thread_id = current_thread.name().unwrap();
59
60        let log_request_response = format!("\n\nRequest (thread id: {} peer address is {}):\n  {} {} {}  {}\n  Body: {} byte(s) total (including default initialization vector)\nEnd of Request\nResponse:\n  {} {} {}\n\n  Body: {} part(s), {} byte(s) total\nEnd of Response",
61                                           thread_id,
62                                           peer_addr,
63                                           &request.http_version,
64                                           &request.method,
65                                           &request.request_uri,
66                                           request_headers,
67                                           request.body.len(),
68
69                                           &response.status_code,
70                                           &response.reason_phrase,
71                                           response_headers,
72                                           response_body_parts_number,
73                                           response_body_length);
74
75        log_request_response
76    }
77
78    pub fn usage_information() -> String {
79        let mut log = "Usage:\n\n".to_string();
80        let command_line_arg_list = CommandLineArgument::get_command_line_arg_list();
81        for arg in command_line_arg_list {
82            let flags = if arg.short_form.is_empty() {
83                format!("--{}", arg.long_form)
84            } else {
85                format!("-{} or --{}", arg.short_form, arg.long_form)
86            };
87            let argument_info = format!("  {} environment variable\n  {} as command line line argument\n  {}\n\n", arg.environment_variable, flags, arg._hint.unwrap());
88            log = [log, argument_info].join("");
89        }
90        log = [log, "End of usage section\n\n".to_string()].join("");
91        log
92    }
93
94    /// The user rws runs as, for the startup banner: `$USER`, `$LOGNAME` or
95    /// `%USERNAME%`, else `"unknown"`. Deliberately not `whoami` (what
96    /// `FileExt::get_current_user` runs): minimal container images such as
97    /// distroless have no `whoami`, and the banner's `unwrap()` on that
98    /// error crashed the published Docker image at startup.
99    pub fn current_user() -> String {
100        ["USER", "LOGNAME", "USERNAME"]
101            .iter()
102            .find_map(|var| std::env::var(var).ok().filter(|v| !v.trim().is_empty()))
103            .unwrap_or_else(|| "unknown".to_string())
104    }
105
106    pub fn info(name: &str) -> String {
107        let mut log = format!("{}\n", name).to_string();
108        const VERSION: &str = env!("CARGO_PKG_VERSION");
109        const AUTHORS: &str = env!("CARGO_PKG_AUTHORS");
110        const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
111        const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
112        const RUST_VERSION: &str = env!("CARGO_PKG_RUST_VERSION");
113        const LICENSE: &str = env!("CARGO_PKG_LICENSE");
114        let user = Log::current_user();
115        let working_directory = crate::app::controller::static_resource::working_directory().to_string();
116
117        let version = format!("Version:           {}\n", VERSION);
118        log = [log, version].join("");
119
120        let authors = format!("Authors:           {}\n", AUTHORS);
121        log = [log, authors].join("");
122
123        let repository = format!("Repository:        {}\n", REPOSITORY);
124        log = [log, repository].join("");
125
126        let description = format!("Description:       {}\n", DESCRIPTION);
127        log = [log, description].join("");
128
129        let rust_version = format!("Rust Version:      {}\n", RUST_VERSION);
130        log = [log, rust_version].join("");
131
132        let license = format!("License:           {}\n", LICENSE);
133        log = [log, license].join("");
134
135        let license = format!("User:              {}\n", user);
136        log = [log, license].join("");
137
138        let license = format!("Working Directory: {}\n", working_directory);
139        log = [log, license].join("");
140
141        log
142    }
143
144    /// Returns a structured JSON log line for one request/response pair:
145    /// `time`, `remote_addr`, `method`, `path`, `protocol`, `status`, `bytes`,
146    /// then `host`, `user_agent` and `referer` when the request has them.
147    ///
148    /// Enable with `RWS_CONFIG_LOG_FORMAT=json`. Useful for log aggregators
149    /// (Loki, Fluentd, Datadog) that ingest JSON from pod stdout.
150    pub fn json(request: &Request, response: &Response, peer_addr: &SocketAddr) -> String {
151        let mut line = Vec::with_capacity(160);
152        Log::write_json(&mut line, request, response, peer_addr);
153        bytes_to_string(line)
154    }
155
156    /// [`Log::json`] appended to `out`, without intermediate strings.
157    fn write_json(out: &mut Vec<u8>, request: &Request, response: &Response, peer_addr: &SocketAddr) {
158        use std::io::Write;
159        let body_size: usize = response.content_range_list.iter().map(|cr| cr.body.len()).sum();
160        out.extend_from_slice(b"{\"time\":\"");
161        with_timestamps(|iso, _| out.extend_from_slice(iso.as_bytes()));
162        out.extend_from_slice(b"\",\"remote_addr\":\"");
163        let _ = write!(out, "{}", peer_addr.ip());
164        out.extend_from_slice(b"\",\"method\":\"");
165        push_json_escaped(out, &request.method);
166        out.extend_from_slice(b"\",\"path\":\"");
167        push_json_escaped(out, &request.request_uri);
168        out.extend_from_slice(b"\",\"protocol\":\"");
169        push_json_escaped(out, &request.http_version);
170        out.extend_from_slice(b"\",\"status\":");
171        let _ = write!(out, "{}", response.status_code);
172        out.extend_from_slice(b",\"bytes\":");
173        out.extend_from_slice(crate::ext::decimal::Decimal::new(body_size as u128).as_str().as_bytes());
174        // Who asked, for what site, from where (18.15.0): only when sent.
175        for (key, name) in [(&b",\"host\":\""[..], "host"), (&b",\"user_agent\":\""[..], "user-agent"), (&b",\"referer\":\""[..], "referer")] {
176            if let Some(header) = request.header(name).filter(|h| !h.value.is_empty()) {
177                out.extend_from_slice(key);
178                push_json_escaped(out, &header.value);
179                out.push(b'"');
180            }
181        }
182        out.push(b'}');
183    }
184
185    /// Writes one access log line to stdout using the format configured by
186    /// `RWS_CONFIG_LOG_FORMAT` (`"combined"` or `"json"`). Call this instead of
187    /// `Log::combined` so that format selection is centralised.
188    ///
189    /// Lines are buffered per thread and written by a background thread every
190    /// 100 ms (and when a thread's buffer passes 32 KiB, when the thread
191    /// exits, and at process exit); [`Log::flush_access_log`] writes them now.
192    pub fn log_access(request: &Request, response: &Response, peer_addr: &SocketAddr) {
193        // Traffic insights count every request, whether lines are written.
194        crate::traffic::observe(request, response, peer_addr.ip());
195        let config = crate::server_config::ServerConfig::current();
196        let format = &config.log_format;
197        if format.eq_ignore_ascii_case("off") || format.eq_ignore_ascii_case("none") {
198            return;
199        }
200        let json = format == "json";
201        access_sink::write_line(|out| {
202            if json {
203                Log::write_json(out, request, response, peer_addr)
204            } else {
205                Log::write_combined(out, request, response, peer_addr)
206            }
207        });
208    }
209
210    /// Have `SIGUSR1` reopen the access-log file (`RWS_CONFIG_ACCESS_LOG`)
211    /// before its next write, for logrotate; does nothing when the log goes
212    /// to stdout. The `rws` binary calls it at startup.
213    pub fn reopen_access_log_on_sigusr1() {
214        access_sink::install_reopen_signal();
215    }
216
217    /// Reopen the access-log file before its next write — what `SIGUSR1`
218    /// does, for a program that moves the file itself.
219    pub fn reopen_access_log() {
220        access_sink::reopen();
221    }
222
223    /// Write out the buffered access-log lines now (they're otherwise written
224    /// within 100 ms) — e.g. before exiting without returning from `main`.
225    pub fn flush_access_log() {
226        access_sink::flush();
227    }
228
229    /// The access-log line for `RWS_CONFIG_LOG_FORMAT`: `json` (the `rws`
230    /// binary's default), Combined Log Format for any other value (including
231    /// unset, in library use), or `None` for `off`/`none` — no per-request
232    /// line, e.g. behind a proxy that already logs or when benchmarking.
233    /// Taken from `ServerConfig::current()`, so it's hot-reloadable.
234    pub fn access_log_line(request: &Request, response: &Response, peer_addr: &SocketAddr) -> Option<String> {
235        let config = crate::server_config::ServerConfig::current();
236        let format = &config.log_format;
237        if format.eq_ignore_ascii_case("off") || format.eq_ignore_ascii_case("none") {
238            return None;
239        }
240        Some(if format == "json" {
241            Log::json(request, response, peer_addr)
242        } else {
243            Log::combined(request, response, peer_addr)
244        })
245    }
246
247    fn format_iso8601(secs: u64) -> String {
248        let sec = secs % 60;
249        let min = (secs / 60) % 60;
250        let hour = (secs / 3600) % 24;
251        let days = secs / 86400;
252        let (year, month, day) = Log::days_to_ymd(days);
253        format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", year, month, day, hour, min, sec)
254    }
255
256    /// Returns a Combined Log Format (CLF) line for one request/response pair:
257    /// `IP - - [DD/Mon/YYYY:HH:MM:SS +0000] "METHOD URI VERSION" STATUS SIZE`
258    pub fn combined(request: &Request, response: &Response, peer_addr: &SocketAddr) -> String {
259        let mut line = Vec::with_capacity(128);
260        Log::write_combined(&mut line, request, response, peer_addr);
261        bytes_to_string(line)
262    }
263
264    /// [`Log::combined`] appended to `out`, without intermediate strings.
265    fn write_combined(out: &mut Vec<u8>, request: &Request, response: &Response, peer_addr: &SocketAddr) {
266        use std::io::Write;
267        let body_size: usize = response.content_range_list.iter().map(|cr| cr.body.len()).sum();
268        let _ = write!(out, "{}", peer_addr.ip());
269        out.extend_from_slice(b" - - [");
270        with_timestamps(|_, clf| out.extend_from_slice(clf.as_bytes()));
271        out.extend_from_slice(b"] \"");
272        out.extend_from_slice(request.method.as_bytes());
273        out.push(b' ');
274        out.extend_from_slice(request.request_uri.as_bytes());
275        out.push(b' ');
276        out.extend_from_slice(request.http_version.as_bytes());
277        out.extend_from_slice(b"\" ");
278        let _ = write!(out, "{}", response.status_code);
279        out.push(b' ');
280        if body_size > 0 {
281            out.extend_from_slice(crate::ext::decimal::Decimal::new(body_size as u128).as_str().as_bytes());
282        } else {
283            out.push(b'-');
284        }
285    }
286
287    fn format_clf_timestamp(secs: u64) -> String {
288        let sec = secs % 60;
289        let min = (secs / 60) % 60;
290        let hour = (secs / 3600) % 24;
291        let days = secs / 86400;
292        let (year, month, day) = Log::days_to_ymd(days);
293        const MONTHS: [&str; 12] = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
294        format!("{:02}/{}/{:04}:{:02}:{:02}:{:02} +0000",
295            day, MONTHS[(month - 1) as usize], year, hour, min, sec)
296    }
297
298    fn days_to_ymd(days: u64) -> (u64, u64, u64) {
299        let z = days + 719468;
300        let era = z / 146097;
301        let doe = z % 146097;
302        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
303        let y = yoe + era * 400;
304        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
305        let mp = (5 * doy + 2) / 153;
306        let d = doy - (153 * mp + 2) / 5 + 1;
307        let m = if mp < 10 { mp + 3 } else { mp - 9 };
308        let y = if m <= 2 { y + 1 } else { y };
309        (y, m, d)
310    }
311
312    pub fn server_url_thread_count(protocol: &str, bind_addr: &String, thread_count: i32) -> String {
313        let url = format!("Server is up and running at: {}://{}\n", protocol, &bind_addr);
314        let thread_count = format!("Spawned {} thread(s) to handle incoming requests\n", thread_count);
315        [url, thread_count].join("")
316    }
317}
318/// The current second as ISO 8601 (`2026-10-29T12:00:00Z`), cached per
319/// thread like the access log's.
320pub(crate) fn iso8601_now(use_it: impl FnOnce(&str)) {
321    with_timestamps(|iso, _| use_it(iso));
322}
323
324/// The current second's ISO 8601 and Combined Log Format timestamps,
325/// formatted at most once per second per thread.
326fn with_timestamps(use_them: impl FnOnce(&str, &str)) {
327    use std::cell::RefCell;
328    use std::time::{SystemTime, UNIX_EPOCH};
329    thread_local! {
330        static CACHED: RefCell<(u64, String, String)> = const { RefCell::new((u64::MAX, String::new(), String::new())) };
331    }
332    let secs = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
333    CACHED.with(|cached| {
334        let mut cached = cached.borrow_mut();
335        if cached.0 != secs {
336            *cached = (secs, Log::format_iso8601(secs), Log::format_clf_timestamp(secs));
337        }
338        use_them(&cached.1, &cached.2);
339    });
340}
341
342/// `s` JSON-escaped as the access log always did it: backslash, double
343/// quote, newline and carriage return.
344fn push_json_escaped(out: &mut Vec<u8>, s: &str) {
345    for b in s.bytes() {
346        match b {
347            b'\\' => out.extend_from_slice(b"\\\\"),
348            b'"' => out.extend_from_slice(b"\\\""),
349            b'\n' => out.extend_from_slice(b"\\n"),
350            b'\r' => out.extend_from_slice(b"\\r"),
351            _ => out.push(b),
352        }
353    }
354}
355
356/// A line built only from `&str` pieces is UTF-8.
357fn bytes_to_string(bytes: Vec<u8>) -> String {
358    String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
359}