hyperlane_plugin_logger/impl.rs
1use super::*;
2
3/// Formatting / debug-printing for [`LoggerConfig`].
4impl Debug for LoggerConfig {
5 /// Formats the [`LoggerConfig`] without requiring [`LogSink`] to implement [`Debug`].
6 ///
7 /// # Arguments
8 ///
9 /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
10 ///
11 /// # Returns
12 ///
13 /// - `fmt::Result` - Formatting status.
14 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 f.debug_struct(DEBUG_LOGGER_CONFIG)
16 .field(DEBUG_FIELD_LEVEL, &self.level)
17 .field(DEBUG_FIELD_FILE, &self.file)
18 .field(DEBUG_FIELD_CONSOLE, &self.console)
19 .field(DEBUG_FIELD_FORMAT, &self.format)
20 .field(DEBUG_FIELD_CHANNEL_CAPACITY, &self.channel_capacity)
21 .field(DEBUG_FIELD_HAS_SINK, &self.sink.is_some())
22 .finish()
23 }
24}
25
26/// Default construction for [`LoggerConfig`].
27impl Default for LoggerConfig {
28 /// Builds the configuration the logger uses when none is given.
29 ///
30 /// # Returns
31 ///
32 /// - `Self` - The default configuration.
33 fn default() -> Self {
34 Self {
35 level: LevelFilter::Info,
36 file: None,
37 console: true,
38 format: LogFormat::Plain,
39 channel_capacity: DEFAULT_LOGGER_CHANNEL_CAPACITY,
40 sink: None,
41 }
42 }
43}
44
45/// Inherent implementation of [`LoggerConfig`].
46impl LoggerConfig {
47 /// Creates a new [`LoggerConfig`] with the specified maximum log level.
48 ///
49 /// # Arguments
50 ///
51 /// - `LevelFilter` - Maximum severity level written by the logger.
52 ///
53 /// # Returns
54 ///
55 /// - `Self` - Constructed configuration.
56 pub fn new(level: LevelFilter) -> Self {
57 Self {
58 level,
59 ..Self::default()
60 }
61 }
62
63 /// Returns the configured maximum [`LevelFilter`].
64 ///
65 /// # Returns
66 ///
67 /// - `LevelFilter` - Active maximum log level.
68 pub fn get_level(&self) -> LevelFilter {
69 self.level
70 }
71
72 /// Returns the optional log file path.
73 ///
74 /// # Returns
75 ///
76 /// - `Option<&str>` - Configured log file path, if any.
77 pub fn get_file(&self) -> Option<&str> {
78 self.file.as_deref()
79 }
80
81 /// Returns whether standard output console logging is enabled.
82 ///
83 /// # Returns
84 ///
85 /// - `bool` - `true` when console logging is enabled.
86 pub fn get_console(&self) -> bool {
87 self.console
88 }
89
90 /// Returns the active [`LogFormat`].
91 ///
92 /// # Returns
93 ///
94 /// - `LogFormat` - Plain or JSON output format.
95 pub fn get_format(&self) -> LogFormat {
96 self.format
97 }
98
99 /// Returns the bounded non-blocking background writer channel capacity.
100 ///
101 /// # Returns
102 ///
103 /// - `usize` - Maximum queued log records before dropping.
104 pub fn get_channel_capacity(&self) -> usize {
105 self.channel_capacity
106 }
107
108 /// Sets the maximum [`LevelFilter`] in place.
109 ///
110 /// # Arguments
111 ///
112 /// - `LevelFilter` - Desired maximum severity level.
113 ///
114 /// # Returns
115 ///
116 /// - `&mut Self` - Mutable reference for fluent chaining.
117 pub fn set_level(&mut self, level: LevelFilter) -> &mut Self {
118 self.level = level;
119 self
120 }
121
122 /// Sets the optional log file path in place.
123 ///
124 /// # Arguments
125 ///
126 /// - `Option<String>` - Optional destination file path.
127 ///
128 /// # Returns
129 ///
130 /// - `&mut Self` - Mutable reference for fluent chaining.
131 pub fn set_file(&mut self, file: Option<String>) -> &mut Self {
132 self.file = file;
133 self
134 }
135
136 /// Enables or disables standard output console printing in place.
137 ///
138 /// # Arguments
139 ///
140 /// - `bool` - `true` to write to stdout, `false` to skip console output.
141 ///
142 /// # Returns
143 ///
144 /// - `&mut Self` - Mutable reference for fluent chaining.
145 pub fn set_console(&mut self, enabled: bool) -> &mut Self {
146 self.console = enabled;
147 self
148 }
149
150 /// Selects the [`LogFormat`] in place.
151 ///
152 /// # Arguments
153 ///
154 /// - `LogFormat` - Desired record wire format.
155 ///
156 /// # Returns
157 ///
158 /// - `&mut Self` - Mutable reference for fluent chaining.
159 pub fn set_format(&mut self, format: LogFormat) -> &mut Self {
160 self.format = format;
161 self
162 }
163
164 /// Sets the bounded background channel capacity in place.
165 ///
166 /// # Arguments
167 ///
168 /// - `usize` - Channel capacity (clamped to `>= 1`).
169 ///
170 /// # Returns
171 ///
172 /// - `&mut Self` - Mutable reference for fluent chaining.
173 pub fn set_channel_capacity(&mut self, capacity: usize) -> &mut Self {
174 self.channel_capacity = capacity.max(1);
175 self
176 }
177
178 /// Sets the custom extensible [`LogSink`] in place.
179 ///
180 /// # Arguments
181 ///
182 /// - `Option<SharedLogSink>` - Optional custom sink implementation.
183 ///
184 /// # Returns
185 ///
186 /// - `&mut Self` - Mutable reference for fluent chaining.
187 pub fn set_sink(&mut self, sink: Option<SharedLogSink>) -> &mut Self {
188 self.sink = sink;
189 self
190 }
191
192 /// Updates the maximum [`LevelFilter`].
193 ///
194 /// # Arguments
195 ///
196 /// - `LevelFilter` - Desired maximum severity level.
197 ///
198 /// # Returns
199 ///
200 /// - `Self` - Updated configuration.
201 pub fn with_level(mut self, level: LevelFilter) -> Self {
202 self.set_level(level);
203 self
204 }
205
206 /// Configures a file path for non-blocking buffered append logging.
207 ///
208 /// # Arguments
209 ///
210 /// - `P` - Destination file path convertible into `String`.
211 ///
212 /// # Returns
213 ///
214 /// - `Self` - Updated configuration.
215 pub fn with_file<P>(mut self, path: P) -> Self
216 where
217 P: Into<String>,
218 {
219 self.set_file(Some(path.into()));
220 self
221 }
222
223 /// Enables or disables standard output console printing.
224 ///
225 /// # Arguments
226 ///
227 /// - `bool` - `true` to write to stdout, `false` to skip console output.
228 ///
229 /// # Returns
230 ///
231 /// - `Self` - Updated configuration.
232 pub fn with_console(mut self, enabled: bool) -> Self {
233 self.set_console(enabled);
234 self
235 }
236
237 /// Selects the [`LogFormat`] emitted by the logger.
238 ///
239 /// # Arguments
240 ///
241 /// - `LogFormat` - Desired record wire format.
242 ///
243 /// # Returns
244 ///
245 /// - `Self` - Updated configuration.
246 pub fn with_format(mut self, format: LogFormat) -> Self {
247 self.set_format(format);
248 self
249 }
250
251 /// Sets the bounded background channel capacity for non-blocking file I/O.
252 ///
253 /// # Arguments
254 ///
255 /// - `usize` - Channel capacity (clamped to `>= 1`).
256 ///
257 /// # Returns
258 ///
259 /// - `Self` - Updated configuration.
260 pub fn with_channel_capacity(mut self, capacity: usize) -> Self {
261 self.set_channel_capacity(capacity);
262 self
263 }
264
265 /// Attaches a custom extensible [`LogSink`] to receive every formatted log record.
266 ///
267 /// # Arguments
268 ///
269 /// - `SharedLogSink` - Custom sink implementation.
270 ///
271 /// # Returns
272 ///
273 /// - `Self` - Updated configuration.
274 pub fn with_sink(mut self, sink: SharedLogSink) -> Self {
275 self.set_sink(Some(sink));
276 self
277 }
278}
279
280/// Implements `impl log::Log for LoggerPlugin`.
281impl log::Log for LoggerPlugin {
282 /// Reports whether the level is written.
283 ///
284 /// # Arguments
285 ///
286 /// - `&Metadata<'_>` - The metadata of the record.
287 ///
288 /// # Returns
289 ///
290 /// - `bool` - Whether the record is written.
291 fn enabled(&self, metadata: &Metadata<'_>) -> bool {
292 CONFIG
293 .get()
294 .is_none_or(|config: &LoggerConfig| metadata.level() <= config.get_level())
295 }
296
297 /// Writes one sanitized record without blocking request threads on file I/O.
298 ///
299 /// # Arguments
300 ///
301 /// - `&Record<'_>` - The record to write.
302 fn log(&self, record: &Record<'_>) {
303 if !self.enabled(record.metadata()) {
304 return;
305 }
306 let config_opt: Option<&LoggerConfig> = CONFIG.get();
307 let format: LogFormat = config_opt.map_or(LogFormat::Plain, LoggerConfig::get_format);
308 let console: bool = config_opt.is_none_or(LoggerConfig::get_console);
309 let line: String = format_log_record(record, format);
310 if let Some(config) = config_opt
311 && let Some(sink) = config.sink.as_ref()
312 {
313 sink.write_record(record.level().to_level_filter(), &line);
314 }
315 if let Some(Some(tx)) = WRITER_TX.get()
316 && tx.try_send(WriterCommand::Line(line.clone())).is_err()
317 {
318 DROPPED_RECORDS.fetch_add(1, Ordering::Relaxed);
319 }
320 if console {
321 let mut out: io::StdoutLock<'static> = stdout().lock();
322 let _: io::Result<()> = out.write_all(line.as_bytes());
323 let _: io::Result<()> = out.write_all(b"\n");
324 }
325 }
326
327 /// Flushes the background file writer and any attached custom sink.
328 fn flush(&self) {
329 if let Some(Some(tx)) = WRITER_TX.get() {
330 let (ack_tx, ack_rx): (SyncSender<()>, Receiver<()>) = sync_channel(1);
331 if tx.send(WriterCommand::Flush(ack_tx)).is_ok() {
332 let _: Result<(), RecvError> = ack_rx.recv();
333 }
334 }
335 if let Some(config) = CONFIG.get()
336 && let Some(sink) = config.sink.as_ref()
337 {
338 sink.flush();
339 }
340 }
341}
342
343/// Inherent implementation of [`LoggerPlugin`].
344impl LoggerPlugin {
345 /// Escapes CR, LF, ESC, and control characters to prevent log forging and terminal injection.
346 ///
347 /// # Arguments
348 ///
349 /// - `&str` - Raw log text.
350 ///
351 /// # Returns
352 ///
353 /// - `String` - Single-line sanitized log text.
354 pub fn sanitize_log_text(input: &str) -> String {
355 let mut out: String = String::with_capacity(input.len());
356 push_sanitized_plain(input, &mut out);
357 out
358 }
359
360 /// Installs the logger with non-blocking buffered file output when configured.
361 ///
362 /// # Arguments
363 ///
364 /// - `LoggerConfig` - The configuration to work from.
365 ///
366 /// # Returns
367 ///
368 /// - `Result<(), String>` - Nothing, or the reason the logger was refused.
369 pub fn init(config: LoggerConfig) -> Result<(), String> {
370 if CONFIG.get().is_some() {
371 return Err(ERROR_CONFIG_ALREADY_SET.to_owned());
372 }
373 if WRITER_TX.get().is_some() {
374 return Err(ERROR_FILE_ALREADY_SET.to_owned());
375 }
376 let writer_tx: Option<SyncSender<WriterCommand>> = match config.get_file() {
377 Some(path) => {
378 let file: File = OpenOptions::new()
379 .create(true)
380 .append(true)
381 .open(path)
382 .map_err(|error: io::Error| {
383 format!("the log file could not be opened: {error}")
384 })?;
385 Some(spawn_file_writer(file, config.get_channel_capacity())?)
386 }
387 None => None,
388 };
389 let level: LevelFilter = config.get_level();
390 set_logger(&LoggerPlugin)
391 .map_err(|_: SetLoggerError| ERROR_LOGGER_ALREADY_INSTALLED.to_owned())?;
392 WRITER_TX
393 .set(writer_tx)
394 .map_err(|_: Option<SyncSender<WriterCommand>>| ERROR_FILE_ALREADY_SET.to_owned())?;
395 CONFIG
396 .set(config)
397 .map_err(|_: LoggerConfig| ERROR_CONFIG_ALREADY_SET.to_owned())?;
398 set_max_level(level);
399 Ok(())
400 }
401
402 /// The configuration the logger works from.
403 ///
404 /// # Returns
405 ///
406 /// - `Option<&'static LoggerConfig>` - The configuration, when it was set.
407 pub fn get() -> Option<&'static LoggerConfig> {
408 CONFIG.get()
409 }
410
411 /// Returns the total number of log records dropped due to background writer backpressure.
412 ///
413 /// # Returns
414 ///
415 /// - `u64` - Cumulative dropped record count.
416 pub fn dropped_count() -> u64 {
417 DROPPED_RECORDS.load(Ordering::Relaxed)
418 }
419
420 /// Writes a line at the info level.
421 ///
422 /// # Arguments
423 ///
424 /// - `T` - The line to write.
425 pub fn log_info<T>(data: T)
426 where
427 T: AsRef<str>,
428 {
429 log::info!("{}", data.as_ref());
430 }
431
432 /// Writes a line at the error level.
433 ///
434 /// # Arguments
435 ///
436 /// - `T` - The line to write.
437 pub fn log_error<T>(data: T)
438 where
439 T: AsRef<str>,
440 {
441 log::error!("{}", data.as_ref());
442 }
443
444 /// Writes a line at the warn level.
445 ///
446 /// # Arguments
447 ///
448 /// - `T` - The line to write.
449 pub fn log_warn<T>(data: T)
450 where
451 T: AsRef<str>,
452 {
453 log::warn!("{}", data.as_ref());
454 }
455
456 /// Writes a line at the debug level.
457 ///
458 /// # Arguments
459 ///
460 /// - `T` - The line to write.
461 pub fn log_debug<T>(data: T)
462 where
463 T: AsRef<str>,
464 {
465 log::debug!("{}", data.as_ref());
466 }
467
468 /// Writes a line at the trace level.
469 ///
470 /// # Arguments
471 ///
472 /// - `T` - The line to write.
473 pub fn log_trace<T>(data: T)
474 where
475 T: AsRef<str>,
476 {
477 log::trace!("{}", data.as_ref());
478 }
479}
480
481/// Implements [`ServerHook`] for [`RequestLogger`].
482impl ServerHook for RequestLogger {
483 /// Builds the middleware.
484 ///
485 /// # Arguments
486 ///
487 /// - `&mut Stream` - The stream the request arrived on.
488 /// - `&mut Context` - The context of the request.
489 ///
490 /// # Returns
491 ///
492 /// - `Self` - The middleware.
493 async fn new(_: &mut Stream, _: &mut Context) -> Self {
494 Self
495 }
496
497 /// Notes when the request arrived.
498 ///
499 /// # Arguments
500 ///
501 /// - `Self` - The middleware.
502 /// - `&mut Stream` - The stream the request arrived on.
503 /// - `&mut Context` - The context of the request.
504 ///
505 /// # Returns
506 ///
507 /// - `Status` - Whether the pipeline continues.
508 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
509 if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
510 return Status::Continue;
511 }
512 ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
513 Status::Continue
514 }
515}
516
517/// Implements [`ServerHook`] for [`ResponseLogger`].
518impl ServerHook for ResponseLogger {
519 /// Builds the middleware.
520 ///
521 /// # Arguments
522 ///
523 /// - `&mut Stream` - The stream the request arrived on.
524 /// - `&mut Context` - The context of the request.
525 ///
526 /// # Returns
527 ///
528 /// - `Self` - The middleware.
529 async fn new(_: &mut Stream, _: &mut Context) -> Self {
530 Self
531 }
532
533 /// Writes the line of the answered request.
534 ///
535 /// # Arguments
536 ///
537 /// - `Self` - The middleware.
538 /// - `&mut Stream` - The stream the request arrived on.
539 /// - `&mut Context` - The context of the request.
540 ///
541 /// # Returns
542 ///
543 /// - `Status` - Whether the pipeline continues.
544 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
545 if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
546 return Status::Continue;
547 }
548 let started_at: Option<Instant> = ctx.try_get_attribute(ATTRIBUTE_STARTED_AT);
549 let elapsed: u128 = match started_at {
550 Some(started_at) => started_at.elapsed().as_millis(),
551 None => 0,
552 };
553 let method: &RequestMethod = ctx.get_request().get_method();
554 let path: &str = ctx.get_request().get_path().as_str();
555 let status: usize = ctx.get_response().get_status_code();
556 let method_text: String = method.to_string();
557 log::info!(
558 "{} {} {} {}ms",
559 if method_text.is_empty() {
560 METHOD_UNKNOWN
561 } else {
562 method_text.as_str()
563 },
564 if path.is_empty() { PATH_UNKNOWN } else { path },
565 status,
566 elapsed
567 );
568 Status::Continue
569 }
570}