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