Skip to main content

hyperlane_plugin_logger/
impl.rs

1use super::*;
2
3/// Default construction for [`LoggerConfig`].
4impl Default for LoggerConfig {
5    /// Builds the configuration the logger uses when none is given.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - The default configuration.
10    fn default() -> Self {
11        Self {
12            level: LevelFilter::Info,
13            file: None,
14        }
15    }
16}
17
18/// Implements `impl log::Log for LoggerPlugin`.
19impl log::Log for LoggerPlugin {
20    /// Reports whether the level is written.
21    ///
22    /// # Arguments
23    ///
24    /// - `&Metadata<'_>` - The metadata of the record.
25    ///
26    /// # Returns
27    ///
28    /// - `bool` - Whether the record is written.
29    fn enabled(&self, _: &Metadata<'_>) -> bool {
30        true
31    }
32
33    /// Writes one record.
34    ///
35    /// # Arguments
36    ///
37    /// - `&Record<'_>` - The record to write.
38    fn log(&self, record: &Record<'_>) {
39        let line: String = format!("{} {}", record.level(), record.args());
40        if let Some(file) = FILE.get()
41            && let Ok(mut file) = file.lock()
42            && let Some(file) = file.as_mut()
43        {
44            let _: Result<(), Error> = writeln!(file, "{line}");
45        }
46        println!("{line}");
47    }
48
49    /// Flushes the file the log is appended to.
50    fn flush(&self) {
51        if let Some(file) = FILE.get()
52            && let Ok(mut file) = file.lock()
53            && let Some(file) = file.as_mut()
54        {
55            let _: Result<(), Error> = file.flush();
56        }
57    }
58}
59
60/// Inherent implementation of [`LoggerPlugin`].
61impl LoggerPlugin {
62    /// Installs the logger.
63    ///
64    /// # Arguments
65    ///
66    /// - `LoggerConfig` - The configuration to work from.
67    ///
68    /// # Returns
69    ///
70    /// - `Result<(), String>` - Nothing, or the reason the logger was refused.
71    pub fn init(config: LoggerConfig) -> Result<(), String> {
72        let file: Option<File> = match config.file.as_ref() {
73            Some(path) => match OpenOptions::new().create(true).append(true).open(path) {
74                Ok(file) => Some(file),
75                Err(error) => return Err(format!("the log file could not be opened: {error}")),
76            },
77            None => None,
78        };
79        CONFIG
80            .set(config)
81            .map_err(|_: LoggerConfig| "the logger configuration was already set".to_owned())?;
82        FILE.set(Mutex::new(file))
83            .map_err(|_: Mutex<Option<File>>| "the log file was already set".to_owned())?;
84        set_logger(&LoggerPlugin)
85            .map_err(|_: SetLoggerError| "a logger was already installed".to_owned())?;
86        set_max_level(
87            CONFIG
88                .get()
89                .map(|config: &LoggerConfig| config.level)
90                .unwrap_or(LevelFilter::Info),
91        );
92        Ok(())
93    }
94
95    /// The configuration the logger works from.
96    ///
97    /// # Returns
98    ///
99    /// - `Option<&'static LoggerConfig>` - The configuration, when it was set.
100    pub fn get() -> Option<&'static LoggerConfig> {
101        CONFIG.get()
102    }
103
104    /// Writes a line at the info level.
105    ///
106    /// # Arguments
107    ///
108    /// - `T` - The line to write.
109    pub fn log_info<T>(data: T)
110    where
111        T: AsRef<str>,
112    {
113        log::info!("{}", data.as_ref());
114    }
115
116    /// Writes a line at the error level.
117    ///
118    /// # Arguments
119    ///
120    /// - `T` - The line to write.
121    pub fn log_error<T>(data: T)
122    where
123        T: AsRef<str>,
124    {
125        log::error!("{}", data.as_ref());
126    }
127
128    /// Writes a line at the warn level.
129    ///
130    /// # Arguments
131    ///
132    /// - `T` - The line to write.
133    pub fn log_warn<T>(data: T)
134    where
135        T: AsRef<str>,
136    {
137        log::warn!("{}", data.as_ref());
138    }
139
140    /// Writes a line at the debug level.
141    ///
142    /// # Arguments
143    ///
144    /// - `T` - The line to write.
145    pub fn log_debug<T>(data: T)
146    where
147        T: AsRef<str>,
148    {
149        log::debug!("{}", data.as_ref());
150    }
151
152    /// Writes a line at the trace level.
153    ///
154    /// # Arguments
155    ///
156    /// - `T` - The line to write.
157    pub fn log_trace<T>(data: T)
158    where
159        T: AsRef<str>,
160    {
161        log::trace!("{}", data.as_ref());
162    }
163}
164
165/// Implements [`ServerHook`] for [`RequestLogger`].
166impl ServerHook for RequestLogger {
167    /// Builds the middleware.
168    ///
169    /// # Arguments
170    ///
171    /// - `&mut Stream` - The stream the request arrived on.
172    /// - `&mut Context` - The context of the request.
173    ///
174    /// # Returns
175    ///
176    /// - `Self` - The middleware.
177    async fn new(_: &mut Stream, _: &mut Context) -> Self {
178        Self
179    }
180
181    /// Notes when the request arrived.
182    ///
183    /// # Arguments
184    ///
185    /// - `Self` - The middleware.
186    /// - `&mut Stream` - The stream the request arrived on.
187    /// - `&mut Context` - The context of the request.
188    ///
189    /// # Returns
190    ///
191    /// - `Status` - Whether the pipeline continues.
192    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
193        if CONFIG.get().is_none() {
194            return Status::Continue;
195        }
196        ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
197        Status::Continue
198    }
199}
200
201/// Implements [`ServerHook`] for [`ResponseLogger`].
202impl ServerHook for ResponseLogger {
203    /// Builds the middleware.
204    ///
205    /// # Arguments
206    ///
207    /// - `&mut Stream` - The stream the request arrived on.
208    /// - `&mut Context` - The context of the request.
209    ///
210    /// # Returns
211    ///
212    /// - `Self` - The middleware.
213    async fn new(_: &mut Stream, _: &mut Context) -> Self {
214        Self
215    }
216
217    /// Writes the line of the answered request.
218    ///
219    /// # Arguments
220    ///
221    /// - `Self` - The middleware.
222    /// - `&mut Stream` - The stream the request arrived on.
223    /// - `&mut Context` - The context of the request.
224    ///
225    /// # Returns
226    ///
227    /// - `Status` - Whether the pipeline continues.
228    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
229        if CONFIG.get().is_none() {
230            return Status::Continue;
231        }
232        let started_at: Option<Instant> = ctx.try_get_attribute(ATTRIBUTE_STARTED_AT);
233        let elapsed: u128 = match started_at {
234            Some(started_at) => started_at.elapsed().as_millis(),
235            None => 0,
236        };
237        let method: String = ctx.get_request().get_method().to_string();
238        let path: String = ctx.get_request().get_path().to_owned();
239        let status: usize = ctx.get_response().get_status_code();
240        log::info!(
241            "{} {} {} {}ms",
242            if method.is_empty() {
243                METHOD_UNKNOWN
244            } else {
245                method.as_str()
246            },
247            if path.is_empty() {
248                PATH_UNKNOWN
249            } else {
250                path.as_str()
251            },
252            status,
253            elapsed
254        );
255        Status::Continue
256    }
257}