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<Arc<dyn LogSink>>` - 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<Arc<dyn LogSink>>) -> &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 /// - `Arc<dyn LogSink>` - Custom sink implementation.
313 ///
314 /// # Returns
315 ///
316 /// - `Self` - Updated configuration.
317 pub fn with_sink(mut self, sink: Arc<dyn LogSink>) -> 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<&Arc<dyn LogSink>> =
356 config_opt.and_then(|c: &LoggerConfig| c.sink.as_ref());
357 let writer_tx: Option<&SyncSender<WriterCommand>> =
358 if config_opt.is_some_and(|c: &LoggerConfig| c.get_file().is_some()) {
359 WRITER_TX.get().and_then(Option::as_ref)
360 } else {
361 None
362 };
363 if !console && sink.is_none() && writer_tx.is_none() {
364 return;
365 }
366 let level_filter: LevelFilter = record.level().to_level_filter();
367 if let Some(tx) = writer_tx {
368 let mut line: String = String::with_capacity(128);
369 format_log_record_into(record, format, &mut line);
370 if let Some(custom_sink) = sink {
371 custom_sink.write_record(level_filter, &line);
372 }
373 if console {
374 line.push('\n');
375 let mut out: io::StdoutLock<'static> = stdout().lock();
376 let _: io::Result<()> = out.write_all(line.as_bytes());
377 let _: Option<char> = line.pop();
378 }
379 if tx.try_send(WriterCommand::Line(line)).is_err() {
380 DROPPED_RECORDS.fetch_add(1, Ordering::Relaxed);
381 }
382 return;
383 }
384 let dispatched: bool = LOG_LINE_BUF
385 .try_with(|cell: &RefCell<String>| {
386 if let Ok(mut buf) = cell.try_borrow_mut() {
387 buf.clear();
388 format_log_record_into(record, format, &mut buf);
389 if let Some(custom_sink) = sink {
390 custom_sink.write_record(level_filter, &buf);
391 }
392 if console {
393 buf.push('\n');
394 let mut out: io::StdoutLock<'static> = stdout().lock();
395 let _: io::Result<()> = out.write_all(buf.as_bytes());
396 }
397 if buf.capacity() > 4096 {
398 buf.clear();
399 buf.shrink_to(256);
400 }
401 true
402 } else {
403 false
404 }
405 })
406 .unwrap_or(false);
407 if !dispatched {
408 let mut line: String = String::with_capacity(128);
409 format_log_record_into(record, format, &mut line);
410 if let Some(custom_sink) = sink {
411 custom_sink.write_record(level_filter, &line);
412 }
413 if console {
414 line.push('\n');
415 let mut out: io::StdoutLock<'static> = stdout().lock();
416 let _: io::Result<()> = out.write_all(line.as_bytes());
417 }
418 }
419 }
420
421 /// Flushes the background file writer and any attached custom sink.
422 fn flush(&self) {
423 if let Some(Some(tx)) = WRITER_TX.get() {
424 let (ack_tx, ack_rx): (SyncSender<()>, Receiver<()>) = sync_channel(1);
425 if tx.send(WriterCommand::Flush(ack_tx)).is_ok() {
426 let _: Result<(), RecvError> = ack_rx.recv();
427 }
428 }
429 if let Some(config) = CONFIG.get()
430 && let Some(sink) = config.sink.as_ref()
431 {
432 sink.flush();
433 }
434 }
435}
436
437/// Inherent implementation of [`LoggerPlugin`].
438impl LoggerPlugin {
439 /// Escapes CR, LF, ESC, and control characters to prevent log forging and terminal injection.
440 ///
441 /// # Arguments
442 ///
443 /// - `&str` - Raw log text.
444 ///
445 /// # Returns
446 ///
447 /// - `String` - Single-line sanitized log text.
448 #[inline]
449 pub fn sanitize_log_text(input: &str) -> String {
450 let Some(start) = find_first_plain_unsafe(input.as_bytes()) else {
451 return input.to_owned();
452 };
453 let mut out: String = String::with_capacity(input.len() + 16);
454 push_sanitized_plain_from(input, start, &mut out);
455 out
456 }
457
458 /// Installs the logger with non-blocking buffered file output when configured.
459 ///
460 /// # Arguments
461 ///
462 /// - `LoggerConfig` - The configuration to work from.
463 ///
464 /// # Returns
465 ///
466 /// - `Result<(), String>` - Nothing, or the reason the logger was refused.
467 pub fn init(config: LoggerConfig) -> Result<(), String> {
468 if CONFIG.get().is_some() {
469 return Err(ERROR_CONFIG_ALREADY_SET.to_owned());
470 }
471 if WRITER_TX.get().is_some() {
472 return Err(ERROR_FILE_ALREADY_SET.to_owned());
473 }
474 let writer_tx: Option<SyncSender<WriterCommand>> = match config.get_file() {
475 Some(path) => {
476 let file: File = OpenOptions::new()
477 .create(true)
478 .append(true)
479 .open(path)
480 .map_err(|error: io::Error| {
481 format!("the log file could not be opened: {error}")
482 })?;
483 Some(spawn_file_writer(file, config.get_channel_capacity())?)
484 }
485 None => None,
486 };
487 let level: LevelFilter = config.get_level();
488 set_logger(&LoggerPlugin)
489 .map_err(|_: SetLoggerError| ERROR_LOGGER_ALREADY_INSTALLED.to_owned())?;
490 WRITER_TX
491 .set(writer_tx)
492 .map_err(|_: Option<SyncSender<WriterCommand>>| ERROR_FILE_ALREADY_SET.to_owned())?;
493 CONFIG
494 .set(config)
495 .map_err(|_: LoggerConfig| ERROR_CONFIG_ALREADY_SET.to_owned())?;
496 set_max_level(level);
497 Ok(())
498 }
499
500 /// The configuration the logger works from.
501 ///
502 /// # Returns
503 ///
504 /// - `Option<&'static LoggerConfig>` - The configuration, when it was set.
505 #[inline(always)]
506 pub fn get() -> Option<&'static LoggerConfig> {
507 CONFIG.get()
508 }
509
510 /// Returns the total number of log records dropped due to background writer backpressure.
511 ///
512 /// # Returns
513 ///
514 /// - `u64` - Cumulative dropped record count.
515 #[inline(always)]
516 pub fn dropped_count() -> u64 {
517 DROPPED_RECORDS.load(Ordering::Relaxed)
518 }
519
520 /// Writes a line at the info level.
521 ///
522 /// # Arguments
523 ///
524 /// - `T` - The line to write.
525 pub fn log_info<T>(data: T)
526 where
527 T: AsRef<str>,
528 {
529 log::info!("{}", data.as_ref());
530 }
531
532 /// Writes a line at the error level.
533 ///
534 /// # Arguments
535 ///
536 /// - `T` - The line to write.
537 pub fn log_error<T>(data: T)
538 where
539 T: AsRef<str>,
540 {
541 log::error!("{}", data.as_ref());
542 }
543
544 /// Writes a line at the warn level.
545 ///
546 /// # Arguments
547 ///
548 /// - `T` - The line to write.
549 pub fn log_warn<T>(data: T)
550 where
551 T: AsRef<str>,
552 {
553 log::warn!("{}", data.as_ref());
554 }
555
556 /// Writes a line at the debug level.
557 ///
558 /// # Arguments
559 ///
560 /// - `T` - The line to write.
561 pub fn log_debug<T>(data: T)
562 where
563 T: AsRef<str>,
564 {
565 log::debug!("{}", data.as_ref());
566 }
567
568 /// Writes a line at the trace level.
569 ///
570 /// # Arguments
571 ///
572 /// - `T` - The line to write.
573 pub fn log_trace<T>(data: T)
574 where
575 T: AsRef<str>,
576 {
577 log::trace!("{}", data.as_ref());
578 }
579}
580
581/// Implements [`ServerHook`] for [`RequestLogger`].
582impl ServerHook for RequestLogger {
583 /// Builds the middleware.
584 ///
585 /// # Arguments
586 ///
587 /// - `&mut Stream` - The stream the request arrived on.
588 /// - `&mut Context` - The context of the request.
589 ///
590 /// # Returns
591 ///
592 /// - `Self` - The middleware.
593 #[inline(always)]
594 async fn new(_: &mut Stream, _: &mut Context) -> Self {
595 Self
596 }
597
598 /// Notes when the request arrived.
599 ///
600 /// # Arguments
601 ///
602 /// - `Self` - The middleware.
603 /// - `&mut Stream` - The stream the request arrived on.
604 /// - `&mut Context` - The context of the request.
605 ///
606 /// # Returns
607 ///
608 /// - `Status` - Whether the pipeline continues.
609 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
610 if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
611 return Status::Continue;
612 }
613 ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
614 Status::Continue
615 }
616}
617
618/// Implements [`ServerHook`] for [`ResponseLogger`].
619impl ServerHook for ResponseLogger {
620 /// Builds the middleware.
621 ///
622 /// # Arguments
623 ///
624 /// - `&mut Stream` - The stream the request arrived on.
625 /// - `&mut Context` - The context of the request.
626 ///
627 /// # Returns
628 ///
629 /// - `Self` - The middleware.
630 #[inline(always)]
631 async fn new(_: &mut Stream, _: &mut Context) -> Self {
632 Self
633 }
634
635 /// Writes the line of the answered request.
636 ///
637 /// # Arguments
638 ///
639 /// - `Self` - The middleware.
640 /// - `&mut Stream` - The stream the request arrived on.
641 /// - `&mut Context` - The context of the request.
642 ///
643 /// # Returns
644 ///
645 /// - `Status` - Whether the pipeline continues.
646 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
647 if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
648 return Status::Continue;
649 }
650 let started_at: Option<&Instant> = ctx.try_get_attribute_ref(ATTRIBUTE_STARTED_AT);
651 let elapsed: u128 = match started_at {
652 Some(started_at) => started_at.elapsed().as_millis(),
653 None => 0,
654 };
655 let method_text: &str = request_method_str(ctx.get_request().get_method());
656 let path: &str = ctx.get_request().get_path().as_str();
657 let status: usize = ctx.get_response().get_status_code();
658 log::info!(
659 "{} {} {} {}ms",
660 method_text,
661 if path.is_empty() { PATH_UNKNOWN } else { path },
662 status,
663 elapsed
664 );
665 Status::Continue
666 }
667}