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: &Metadata<'_>) -> bool {
30 CONFIG
31 .get()
32 .is_none_or(|config: &LoggerConfig| metadata.level() <= config.level)
33 }
34
35 /// Writes one sanitized record without allowing CRLF or terminal control injection.
36 ///
37 /// # Arguments
38 ///
39 /// - `&Record<'_>` - The record to write.
40 fn log(&self, record: &Record<'_>) {
41 if !self.enabled(record.metadata()) {
42 return;
43 }
44 let raw_message: String = format!("{}", record.args());
45 let safe_message: String = Self::sanitize_log_text(&raw_message);
46 let line: String = format!("{} {}", record.level(), safe_message);
47 if let Some(file) = FILE.get()
48 && let Ok(mut file) = file.lock()
49 && let Some(file) = file.as_mut()
50 {
51 let _: Result<(), Error> = writeln!(file, "{line}");
52 }
53 println!("{line}");
54 }
55
56 /// Flushes the file the log is appended to.
57 fn flush(&self) {
58 if let Some(file) = FILE.get()
59 && let Ok(mut file) = file.lock()
60 && let Some(file) = file.as_mut()
61 {
62 let _: Result<(), Error> = file.flush();
63 }
64 }
65}
66
67/// Inherent implementation of [`LoggerPlugin`].
68impl LoggerPlugin {
69 /// Escapes CR, LF, ESC, and control characters to prevent log forging and terminal injection.
70 ///
71 /// # Arguments
72 ///
73 /// - `&str` - Raw log text.
74 ///
75 /// # Returns
76 ///
77 /// - `String` - Single-line sanitized log text.
78 pub(crate) fn sanitize_log_text(input: &str) -> String {
79 let mut out: String = String::with_capacity(input.len());
80 for ch in input.chars() {
81 match ch {
82 '\r' => out.push_str(ESCAPED_CR),
83 '\n' => out.push_str(ESCAPED_LF),
84 '\x1b' => out.push_str(ESCAPED_ESC),
85 '\t' => out.push('\t'),
86 c if c.is_control() => out.push(' '),
87 c => out.push(c),
88 }
89 }
90 out
91 }
92
93 /// Installs the logger.
94 ///
95 /// # Arguments
96 ///
97 /// - `LoggerConfig` - The configuration to work from.
98 ///
99 /// # Returns
100 ///
101 /// - `Result<(), String>` - Nothing, or the reason the logger was refused.
102 pub fn init(config: LoggerConfig) -> Result<(), String> {
103 if CONFIG.get().is_some() {
104 return Err(ERROR_CONFIG_ALREADY_SET.to_owned());
105 }
106 if FILE.get().is_some() {
107 return Err(ERROR_FILE_ALREADY_SET.to_owned());
108 }
109 let file: Option<File> = match config.file.as_ref() {
110 Some(path) => match OpenOptions::new().create(true).append(true).open(path) {
111 Ok(file) => Some(file),
112 Err(error) => return Err(format!("the log file could not be opened: {error}")),
113 },
114 None => None,
115 };
116 let level: LevelFilter = config.level;
117 set_logger(&LoggerPlugin)
118 .map_err(|_: SetLoggerError| ERROR_LOGGER_ALREADY_INSTALLED.to_owned())?;
119 FILE.set(Mutex::new(file))
120 .map_err(|_: Mutex<Option<File>>| ERROR_FILE_ALREADY_SET.to_owned())?;
121 CONFIG
122 .set(config)
123 .map_err(|_: LoggerConfig| ERROR_CONFIG_ALREADY_SET.to_owned())?;
124 set_max_level(level);
125 Ok(())
126 }
127
128 /// The configuration the logger works from.
129 ///
130 /// # Returns
131 ///
132 /// - `Option<&'static LoggerConfig>` - The configuration, when it was set.
133 pub fn get() -> Option<&'static LoggerConfig> {
134 CONFIG.get()
135 }
136
137 /// Writes a line at the info level.
138 ///
139 /// # Arguments
140 ///
141 /// - `T` - The line to write.
142 pub fn log_info<T>(data: T)
143 where
144 T: AsRef<str>,
145 {
146 log::info!("{}", data.as_ref());
147 }
148
149 /// Writes a line at the error level.
150 ///
151 /// # Arguments
152 ///
153 /// - `T` - The line to write.
154 pub fn log_error<T>(data: T)
155 where
156 T: AsRef<str>,
157 {
158 log::error!("{}", data.as_ref());
159 }
160
161 /// Writes a line at the warn level.
162 ///
163 /// # Arguments
164 ///
165 /// - `T` - The line to write.
166 pub fn log_warn<T>(data: T)
167 where
168 T: AsRef<str>,
169 {
170 log::warn!("{}", data.as_ref());
171 }
172
173 /// Writes a line at the debug level.
174 ///
175 /// # Arguments
176 ///
177 /// - `T` - The line to write.
178 pub fn log_debug<T>(data: T)
179 where
180 T: AsRef<str>,
181 {
182 log::debug!("{}", data.as_ref());
183 }
184
185 /// Writes a line at the trace level.
186 ///
187 /// # Arguments
188 ///
189 /// - `T` - The line to write.
190 pub fn log_trace<T>(data: T)
191 where
192 T: AsRef<str>,
193 {
194 log::trace!("{}", data.as_ref());
195 }
196}
197
198/// Implements [`ServerHook`] for [`RequestLogger`].
199impl ServerHook for RequestLogger {
200 /// Builds the middleware.
201 ///
202 /// # Arguments
203 ///
204 /// - `&mut Stream` - The stream the request arrived on.
205 /// - `&mut Context` - The context of the request.
206 ///
207 /// # Returns
208 ///
209 /// - `Self` - The middleware.
210 async fn new(_: &mut Stream, _: &mut Context) -> Self {
211 Self
212 }
213
214 /// Notes when the request arrived.
215 ///
216 /// # Arguments
217 ///
218 /// - `Self` - The middleware.
219 /// - `&mut Stream` - The stream the request arrived on.
220 /// - `&mut Context` - The context of the request.
221 ///
222 /// # Returns
223 ///
224 /// - `Status` - Whether the pipeline continues.
225 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
226 if CONFIG.get().is_none() {
227 return Status::Continue;
228 }
229 ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
230 Status::Continue
231 }
232}
233
234/// Implements [`ServerHook`] for [`ResponseLogger`].
235impl ServerHook for ResponseLogger {
236 /// Builds the middleware.
237 ///
238 /// # Arguments
239 ///
240 /// - `&mut Stream` - The stream the request arrived on.
241 /// - `&mut Context` - The context of the request.
242 ///
243 /// # Returns
244 ///
245 /// - `Self` - The middleware.
246 async fn new(_: &mut Stream, _: &mut Context) -> Self {
247 Self
248 }
249
250 /// Writes the line of the answered request.
251 ///
252 /// # Arguments
253 ///
254 /// - `Self` - The middleware.
255 /// - `&mut Stream` - The stream the request arrived on.
256 /// - `&mut Context` - The context of the request.
257 ///
258 /// # Returns
259 ///
260 /// - `Status` - Whether the pipeline continues.
261 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
262 if CONFIG.get().is_none() {
263 return Status::Continue;
264 }
265 let started_at: Option<Instant> = ctx.try_get_attribute(ATTRIBUTE_STARTED_AT);
266 let elapsed: u128 = match started_at {
267 Some(started_at) => started_at.elapsed().as_millis(),
268 None => 0,
269 };
270 let method: String = ctx.get_request().get_method().to_string();
271 let path: String = ctx.get_request().get_path().to_owned();
272 let status: usize = ctx.get_response().get_status_code();
273 log::info!(
274 "{} {} {} {}ms",
275 if method.is_empty() {
276 METHOD_UNKNOWN
277 } else {
278 method.as_str()
279 },
280 if path.is_empty() {
281 PATH_UNKNOWN
282 } else {
283 path.as_str()
284 },
285 status,
286 elapsed
287 );
288 Status::Continue
289 }
290}