torrust_server_lib/logging.rs
1use std::fmt;
2use std::time::Duration;
3
4use tower_http::LatencyUnit;
5
6/// This is the prefix used in logs to identify a started service.
7///
8/// For example:
9///
10/// ```text
11/// 2024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969
12/// 2024-06-25T12:36:25.025445Z INFO HTTP TRACKER: Started on: http://0.0.0.0:7070
13/// 2024-06-25T12:36:25.025527Z INFO API: Started on: http://0.0.0.0:1212
14/// 2024-06-25T12:36:25.025580Z INFO HEALTH CHECK API: Started on: http://127.0.0.1:1313
15/// ```
16pub const STARTED_ON: &str = "Started on";
17
18/*
19
20todo: we should use a field fot the URL.
21
22For example, instead of:
23
24```
252024-06-25T12:36:25.025312Z INFO UDP TRACKER: Started on: udp://0.0.0.0:6969
26```
27
28We should use something like:
29
30```
312024-06-25T12:36:25.025312Z INFO UDP TRACKER started_at_url=udp://0.0.0.0:6969
32```
33
34*/
35
36pub struct Latency {
37 unit: LatencyUnit,
38 duration: Duration,
39}
40
41impl Latency {
42 #[must_use]
43 pub fn new(unit: LatencyUnit, duration: Duration) -> Self {
44 Self { unit, duration }
45 }
46}
47
48impl fmt::Display for Latency {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 match self.unit {
51 LatencyUnit::Seconds => write!(f, "{} s", self.duration.as_secs_f64()),
52 LatencyUnit::Millis => write!(f, "{} ms", self.duration.as_millis()),
53 LatencyUnit::Micros => write!(f, "{} μs", self.duration.as_micros()),
54 LatencyUnit::Nanos => write!(f, "{} ns", self.duration.as_nanos()),
55 _ => panic!("Invalid latency unit"),
56 }
57 }
58}