hyperlane-plugin-logger 23.1.0

A logging plugin for the Hyperlane framework, writing the log of a server to the console, to a file, or to both.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
use super::*;

/// Implements [`fmt::Write`] for [`PlainSanitizingWriter`].
impl fmt::Write for PlainSanitizingWriter<'_> {
    /// Sanitizes and appends `s` directly into the wrapped line buffer.
    ///
    /// # Arguments
    ///
    /// - `&str` - Formatted chunk to sanitize.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Always `Ok(())`.
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let Self { out } = self;
        push_sanitized_plain(s, out);
        Ok(())
    }
}

/// Implements [`fmt::Write`] for [`JsonSanitizingWriter`].
impl fmt::Write for JsonSanitizingWriter<'_> {
    /// JSON-escapes and appends `s` directly into the wrapped line buffer.
    ///
    /// # Arguments
    ///
    /// - `&str` - Formatted chunk to escape.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Always `Ok(())`.
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let Self { out } = self;
        push_sanitized_json(s, out);
        Ok(())
    }
}

/// Formatting / debug-printing for [`LoggerConfig`].
impl Debug for LoggerConfig {
    /// Formats the [`LoggerConfig`] without requiring [`LogSink`] to implement [`Debug`].
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting status.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct(DEBUG_LOGGER_CONFIG)
            .field(DEBUG_FIELD_LEVEL, &self.level)
            .field(DEBUG_FIELD_FILE, &self.file)
            .field(DEBUG_FIELD_CONSOLE, &self.console)
            .field(DEBUG_FIELD_FORMAT, &self.format)
            .field(DEBUG_FIELD_CHANNEL_CAPACITY, &self.channel_capacity)
            .field(DEBUG_FIELD_HAS_SINK, &self.sink.is_some())
            .finish()
    }
}

/// Default construction for [`LoggerConfig`].
impl Default for LoggerConfig {
    /// Builds the configuration the logger uses when none is given.
    ///
    /// # Returns
    ///
    /// - `Self` - The default configuration.
    fn default() -> Self {
        Self {
            level: LevelFilter::Info,
            file: None,
            console: true,
            format: LogFormat::Plain,
            channel_capacity: DEFAULT_LOGGER_CHANNEL_CAPACITY,
            sink: None,
        }
    }
}

/// Inherent implementation of [`LoggerConfig`].
impl LoggerConfig {
    /// Creates a new [`LoggerConfig`] with the specified maximum log level.
    ///
    /// # Arguments
    ///
    /// - `LevelFilter` - Maximum severity level written by the logger.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed configuration.
    pub fn new(level: LevelFilter) -> Self {
        Self {
            level,
            ..Self::default()
        }
    }

    /// Returns the configured maximum [`LevelFilter`].
    ///
    /// # Returns
    ///
    /// - `LevelFilter` - Active maximum log level.
    #[inline(always)]
    pub fn get_level(&self) -> LevelFilter {
        self.level
    }

    /// Returns the optional log file path.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Configured log file path, if any.
    #[inline(always)]
    pub fn get_file(&self) -> Option<&str> {
        self.file.as_deref()
    }

    /// Returns whether standard output console logging is enabled.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when console logging is enabled.
    #[inline(always)]
    pub fn get_console(&self) -> bool {
        self.console
    }

    /// Returns the active [`LogFormat`].
    ///
    /// # Returns
    ///
    /// - `LogFormat` - Plain or JSON output format.
    #[inline(always)]
    pub fn get_format(&self) -> LogFormat {
        self.format
    }

    /// Returns the bounded non-blocking background writer channel capacity.
    ///
    /// # Returns
    ///
    /// - `usize` - Maximum queued log records before dropping.
    #[inline(always)]
    pub fn get_channel_capacity(&self) -> usize {
        self.channel_capacity
    }

    /// Sets the maximum [`LevelFilter`] in place.
    ///
    /// # Arguments
    ///
    /// - `LevelFilter` - Desired maximum severity level.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_level(&mut self, level: LevelFilter) -> &mut Self {
        self.level = level;
        self
    }

    /// Sets the optional log file path in place.
    ///
    /// # Arguments
    ///
    /// - `Option<String>` - Optional destination file path.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_file(&mut self, file: Option<String>) -> &mut Self {
        self.file = file;
        self
    }

    /// Enables or disables standard output console printing in place.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to write to stdout, `false` to skip console output.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_console(&mut self, enabled: bool) -> &mut Self {
        self.console = enabled;
        self
    }

    /// Selects the [`LogFormat`] in place.
    ///
    /// # Arguments
    ///
    /// - `LogFormat` - Desired record wire format.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_format(&mut self, format: LogFormat) -> &mut Self {
        self.format = format;
        self
    }

    /// Sets the bounded background channel capacity in place.
    ///
    /// # Arguments
    ///
    /// - `usize` - Channel capacity (clamped to `>= 1`).
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_channel_capacity(&mut self, capacity: usize) -> &mut Self {
        self.channel_capacity = capacity.max(1);
        self
    }

    /// Sets the custom extensible [`LogSink`] in place.
    ///
    /// # Arguments
    ///
    /// - `Option<Arc<dyn LogSink>>` - Optional custom sink implementation.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for fluent chaining.
    pub fn set_sink(&mut self, sink: Option<Arc<dyn LogSink>>) -> &mut Self {
        self.sink = sink;
        self
    }

    /// Updates the maximum [`LevelFilter`].
    ///
    /// # Arguments
    ///
    /// - `LevelFilter` - Desired maximum severity level.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_level(mut self, level: LevelFilter) -> Self {
        self.set_level(level);
        self
    }

    /// Configures a file path for non-blocking buffered append logging.
    ///
    /// # Arguments
    ///
    /// - `P` - Destination file path convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_file<P>(mut self, path: P) -> Self
    where
        P: Into<String>,
    {
        self.set_file(Some(path.into()));
        self
    }

    /// Enables or disables standard output console printing.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to write to stdout, `false` to skip console output.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_console(mut self, enabled: bool) -> Self {
        self.set_console(enabled);
        self
    }

    /// Selects the [`LogFormat`] emitted by the logger.
    ///
    /// # Arguments
    ///
    /// - `LogFormat` - Desired record wire format.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_format(mut self, format: LogFormat) -> Self {
        self.set_format(format);
        self
    }

    /// Sets the bounded background channel capacity for non-blocking file I/O.
    ///
    /// # Arguments
    ///
    /// - `usize` - Channel capacity (clamped to `>= 1`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_channel_capacity(mut self, capacity: usize) -> Self {
        self.set_channel_capacity(capacity);
        self
    }

    /// Attaches a custom extensible [`LogSink`] to receive every formatted log record.
    ///
    /// # Arguments
    ///
    /// - `Arc<dyn LogSink>` - Custom sink implementation.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_sink(mut self, sink: Arc<dyn LogSink>) -> Self {
        self.set_sink(Some(sink));
        self
    }
}

/// Implements `impl log::Log for LoggerPlugin`.
impl log::Log for LoggerPlugin {
    /// Reports whether the level is written.
    ///
    /// # Arguments
    ///
    /// - `&Metadata<'_>` - The metadata of the record.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the record is written.
    #[inline(always)]
    fn enabled(&self, metadata: &Metadata<'_>) -> bool {
        CONFIG
            .get()
            .is_none_or(|config: &LoggerConfig| metadata.level() <= config.get_level())
    }

    /// Writes one sanitized record without blocking request threads on file I/O.
    ///
    /// # Arguments
    ///
    /// - `&Record<'_>` - The record to write.
    fn log(&self, record: &Record<'_>) {
        let config_opt: Option<&LoggerConfig> = CONFIG.get();
        if let Some(config) = config_opt
            && record.metadata().level() > config.get_level()
        {
            return;
        }
        let format: LogFormat = config_opt.map_or(LogFormat::Plain, LoggerConfig::get_format);
        let console: bool = config_opt.is_none_or(LoggerConfig::get_console);
        let sink: Option<&Arc<dyn LogSink>> =
            config_opt.and_then(|c: &LoggerConfig| c.sink.as_ref());
        let writer_tx: Option<&SyncSender<WriterCommand>> =
            if config_opt.is_some_and(|c: &LoggerConfig| c.get_file().is_some()) {
                WRITER_TX.get().and_then(Option::as_ref)
            } else {
                None
            };
        if !console && sink.is_none() && writer_tx.is_none() {
            return;
        }
        let level_filter: LevelFilter = record.level().to_level_filter();
        if let Some(tx) = writer_tx {
            let mut line: String = String::with_capacity(128);
            format_log_record_into(record, format, &mut line);
            if let Some(custom_sink) = sink {
                custom_sink.write_record(level_filter, &line);
            }
            if console {
                line.push('\n');
                let mut out: io::StdoutLock<'static> = stdout().lock();
                let _: io::Result<()> = out.write_all(line.as_bytes());
                let _: Option<char> = line.pop();
            }
            if tx.try_send(WriterCommand::Line(line)).is_err() {
                DROPPED_RECORDS.fetch_add(1, Ordering::Relaxed);
            }
            return;
        }
        let dispatched: bool = LOG_LINE_BUF
            .try_with(|cell: &RefCell<String>| {
                if let Ok(mut buf) = cell.try_borrow_mut() {
                    buf.clear();
                    format_log_record_into(record, format, &mut buf);
                    if let Some(custom_sink) = sink {
                        custom_sink.write_record(level_filter, &buf);
                    }
                    if console {
                        buf.push('\n');
                        let mut out: io::StdoutLock<'static> = stdout().lock();
                        let _: io::Result<()> = out.write_all(buf.as_bytes());
                    }
                    if buf.capacity() > 4096 {
                        buf.clear();
                        buf.shrink_to(256);
                    }
                    true
                } else {
                    false
                }
            })
            .unwrap_or(false);
        if !dispatched {
            let mut line: String = String::with_capacity(128);
            format_log_record_into(record, format, &mut line);
            if let Some(custom_sink) = sink {
                custom_sink.write_record(level_filter, &line);
            }
            if console {
                line.push('\n');
                let mut out: io::StdoutLock<'static> = stdout().lock();
                let _: io::Result<()> = out.write_all(line.as_bytes());
            }
        }
    }

    /// Flushes the background file writer and any attached custom sink.
    fn flush(&self) {
        if let Some(Some(tx)) = WRITER_TX.get() {
            let (ack_tx, ack_rx): (SyncSender<()>, Receiver<()>) = sync_channel(1);
            if tx.send(WriterCommand::Flush(ack_tx)).is_ok() {
                let _: Result<(), RecvError> = ack_rx.recv();
            }
        }
        if let Some(config) = CONFIG.get()
            && let Some(sink) = config.sink.as_ref()
        {
            sink.flush();
        }
    }
}

/// Inherent implementation of [`LoggerPlugin`].
impl LoggerPlugin {
    /// Escapes CR, LF, ESC, and control characters to prevent log forging and terminal injection.
    ///
    /// # Arguments
    ///
    /// - `&str` - Raw log text.
    ///
    /// # Returns
    ///
    /// - `String` - Single-line sanitized log text.
    #[inline]
    pub fn sanitize_log_text(input: &str) -> String {
        let Some(start) = find_first_plain_unsafe(input.as_bytes()) else {
            return input.to_owned();
        };
        let mut out: String = String::with_capacity(input.len() + 16);
        push_sanitized_plain_from(input, start, &mut out);
        out
    }

    /// Installs the logger with non-blocking buffered file output when configured.
    ///
    /// # Arguments
    ///
    /// - `LoggerConfig` - The configuration to work from.
    ///
    /// # Returns
    ///
    /// - `Result<(), String>` - Nothing, or the reason the logger was refused.
    pub fn init(config: LoggerConfig) -> Result<(), String> {
        if CONFIG.get().is_some() {
            return Err(ERROR_CONFIG_ALREADY_SET.to_owned());
        }
        if WRITER_TX.get().is_some() {
            return Err(ERROR_FILE_ALREADY_SET.to_owned());
        }
        let writer_tx: Option<SyncSender<WriterCommand>> = match config.get_file() {
            Some(path) => {
                let file: File = OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(path)
                    .map_err(|error: io::Error| {
                        format!("the log file could not be opened: {error}")
                    })?;
                Some(spawn_file_writer(file, config.get_channel_capacity())?)
            }
            None => None,
        };
        let level: LevelFilter = config.get_level();
        set_logger(&LoggerPlugin)
            .map_err(|_: SetLoggerError| ERROR_LOGGER_ALREADY_INSTALLED.to_owned())?;
        WRITER_TX
            .set(writer_tx)
            .map_err(|_: Option<SyncSender<WriterCommand>>| ERROR_FILE_ALREADY_SET.to_owned())?;
        CONFIG
            .set(config)
            .map_err(|_: LoggerConfig| ERROR_CONFIG_ALREADY_SET.to_owned())?;
        set_max_level(level);
        Ok(())
    }

    /// The configuration the logger works from.
    ///
    /// # Returns
    ///
    /// - `Option<&'static LoggerConfig>` - The configuration, when it was set.
    #[inline(always)]
    pub fn get() -> Option<&'static LoggerConfig> {
        CONFIG.get()
    }

    /// Returns the total number of log records dropped due to background writer backpressure.
    ///
    /// # Returns
    ///
    /// - `u64` - Cumulative dropped record count.
    #[inline(always)]
    pub fn dropped_count() -> u64 {
        DROPPED_RECORDS.load(Ordering::Relaxed)
    }

    /// Writes a line at the info level.
    ///
    /// # Arguments
    ///
    /// - `T` - The line to write.
    pub fn log_info<T>(data: T)
    where
        T: AsRef<str>,
    {
        log::info!("{}", data.as_ref());
    }

    /// Writes a line at the error level.
    ///
    /// # Arguments
    ///
    /// - `T` - The line to write.
    pub fn log_error<T>(data: T)
    where
        T: AsRef<str>,
    {
        log::error!("{}", data.as_ref());
    }

    /// Writes a line at the warn level.
    ///
    /// # Arguments
    ///
    /// - `T` - The line to write.
    pub fn log_warn<T>(data: T)
    where
        T: AsRef<str>,
    {
        log::warn!("{}", data.as_ref());
    }

    /// Writes a line at the debug level.
    ///
    /// # Arguments
    ///
    /// - `T` - The line to write.
    pub fn log_debug<T>(data: T)
    where
        T: AsRef<str>,
    {
        log::debug!("{}", data.as_ref());
    }

    /// Writes a line at the trace level.
    ///
    /// # Arguments
    ///
    /// - `T` - The line to write.
    pub fn log_trace<T>(data: T)
    where
        T: AsRef<str>,
    {
        log::trace!("{}", data.as_ref());
    }
}

/// Implements [`ServerHook`] for [`RequestLogger`].
impl ServerHook for RequestLogger {
    /// Builds the middleware.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - The stream the request arrived on.
    /// - `&mut Context` - The context of the request.
    ///
    /// # Returns
    ///
    /// - `Self` - The middleware.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Notes when the request arrived.
    ///
    /// # Arguments
    ///
    /// - `Self` - The middleware.
    /// - `&mut Stream` - The stream the request arrived on.
    /// - `&mut Context` - The context of the request.
    ///
    /// # Returns
    ///
    /// - `Status` - Whether the pipeline continues.
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
            return Status::Continue;
        }
        ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now());
        Status::Continue
    }
}

/// Implements [`ServerHook`] for [`ResponseLogger`].
impl ServerHook for ResponseLogger {
    /// Builds the middleware.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - The stream the request arrived on.
    /// - `&mut Context` - The context of the request.
    ///
    /// # Returns
    ///
    /// - `Self` - The middleware.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Writes the line of the answered request.
    ///
    /// # Arguments
    ///
    /// - `Self` - The middleware.
    /// - `&mut Stream` - The stream the request arrived on.
    /// - `&mut Context` - The context of the request.
    ///
    /// # Returns
    ///
    /// - `Status` - Whether the pipeline continues.
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        if CONFIG.get().is_none() || !log_enabled!(Level::Info) {
            return Status::Continue;
        }
        let started_at: Option<Instant> = ctx.try_get_attribute(ATTRIBUTE_STARTED_AT);
        let elapsed: u128 = match started_at {
            Some(started_at) => started_at.elapsed().as_millis(),
            None => 0,
        };
        let method_text: &str = request_method_str(ctx.get_request().get_method());
        let path: &str = ctx.get_request().get_path().as_str();
        let status: usize = ctx.get_response().get_status_code();
        log::info!(
            "{} {} {} {}ms",
            method_text,
            if path.is_empty() { PATH_UNKNOWN } else { path },
            status,
            elapsed
        );
        Status::Continue
    }
}