hyperlane-plugin-logger 22.14.0

A logging plugin for the Hyperlane framework, writing the log of a server to the console, to a file, or to both.
Documentation
use super::*;

/// Resolves a [`RequestMethod`] to a borrowed string slice without allocating.
///
/// # Arguments
///
/// - `&RequestMethod` - Incoming HTTP request method.
///
/// # Returns
///
/// - `&str` - Canonical method string, or [`METHOD_UNKNOWN`] when empty.
#[inline(always)]
pub(crate) fn request_method_str(method: &RequestMethod) -> &str {
    match method {
        RequestMethod::Get => GET,
        RequestMethod::Post => POST,
        RequestMethod::Put => PUT,
        RequestMethod::Delete => DELETE,
        RequestMethod::Patch => PATCH,
        RequestMethod::Head => HEAD,
        RequestMethod::Options => OPTIONS,
        RequestMethod::Connect => CONNECT,
        RequestMethod::Trace => TRACE,
        RequestMethod::Unknown(custom) => {
            if custom.is_empty() {
                METHOD_UNKNOWN
            } else {
                custom.as_str()
            }
        }
    }
}

/// Appends sanitized plain-text characters from `input` into `out` with zero-copy fast path for clean text.
///
/// # Arguments
///
/// - `&str` - Raw input text.
/// - `&mut String` - Destination buffer receiving sanitized text.
#[inline]
pub(crate) fn push_sanitized_plain(input: &str, out: &mut String) {
    let bytes: &[u8] = input.as_bytes();
    let first_bad: Option<usize> = bytes
        .iter()
        .position(|&b: &u8| (b < 0x20 && b != b'\t') || b == 0x7f);
    let Some(start) = first_bad else {
        out.push_str(input);
        return;
    };
    out.push_str(&input[..start]);
    let mut safe_start: usize = start;
    for (rel_idx, ch) in input[start..].char_indices() {
        let abs_idx: usize = start + rel_idx;
        let replacement: Option<&str> = match ch {
            '\r' => Some(ESCAPED_CR),
            '\n' => Some(ESCAPED_LF),
            '\x1b' => Some(ESCAPED_ESC),
            '\t' => None,
            c if c.is_control() => Some(" "),
            _ => None,
        };
        if let Some(esc) = replacement {
            if safe_start < abs_idx {
                out.push_str(&input[safe_start..abs_idx]);
            }
            out.push_str(esc);
            safe_start = abs_idx + ch.len_utf8();
        }
    }
    if safe_start < input.len() {
        out.push_str(&input[safe_start..]);
    }
}

/// Appends JSON-escaped and control-sanitized text from `input` into `out` with zero-copy fast path.
///
/// # Arguments
///
/// - `&str` - Raw text to embed inside a JSON string literal.
/// - `&mut String` - Destination buffer receiving escaped characters.
#[inline]
pub(crate) fn push_sanitized_json(input: &str, out: &mut String) {
    let bytes: &[u8] = input.as_bytes();
    let first_bad: Option<usize> = bytes
        .iter()
        .position(|&b: &u8| b < 0x20 || b == b'"' || b == b'\\' || b == 0x7f);
    let Some(start) = first_bad else {
        out.push_str(input);
        return;
    };
    out.push_str(&input[..start]);
    let mut safe_start: usize = start;
    for (rel_idx, ch) in input[start..].char_indices() {
        let abs_idx: usize = start + rel_idx;
        let replacement: Option<&str> = match ch {
            '"' => Some(ESCAPED_QUOTE),
            '\\' => Some(ESCAPED_BACKSLASH),
            '\r' => Some(ESCAPED_CR),
            '\n' => Some(ESCAPED_LF),
            '\t' => Some(ESCAPED_TAB),
            '\x1b' => Some(ESCAPED_ESC),
            c if c.is_control() => Some(" "),
            _ => None,
        };
        if let Some(esc) = replacement {
            if safe_start < abs_idx {
                out.push_str(&input[safe_start..abs_idx]);
            }
            out.push_str(esc);
            safe_start = abs_idx + ch.len_utf8();
        }
    }
    if safe_start < input.len() {
        out.push_str(&input[safe_start..]);
    }
}

/// Formats one [`Record`] directly into `out` without intermediate message allocations.
///
/// # Arguments
///
/// - `&Record<'_>` - Incoming log record.
/// - `LogFormat` - Output wire format.
/// - `&mut String` - Reusable destination line buffer.
#[inline]
pub(crate) fn format_log_record_into(record: &Record<'_>, format: LogFormat, out: &mut String) {
    let level_str: &str = record.level().as_str();
    match format {
        LogFormat::Plain => {
            out.push_str(level_str);
            out.push(' ');
            if let Some(literal) = record.args().as_str() {
                push_sanitized_plain(literal, out);
            } else {
                let mut writer: PlainSanitizingWriter<'_> = PlainSanitizingWriter { out };
                let _: fmt::Result = fmt::write(&mut writer, *record.args());
            }
        }
        LogFormat::Json => {
            out.push_str(JSON_PREFIX_LEVEL);
            out.push_str(level_str);
            out.push_str(JSON_SEP_TARGET);
            push_sanitized_json(record.target(), out);
            out.push_str(JSON_SEP_MESSAGE);
            if let Some(literal) = record.args().as_str() {
                push_sanitized_json(literal, out);
            } else {
                let mut writer: JsonSanitizingWriter<'_> = JsonSanitizingWriter { out };
                let _: fmt::Result = fmt::write(&mut writer, *record.args());
            }
            out.push_str(JSON_SUFFIX);
        }
    }
}

/// Spawns the dedicated background buffered file writer thread.
///
/// # Arguments
///
/// - `File` - Opened append-mode log file handle.
/// - `usize` - Bounded channel capacity before backpressure drops records.
///
/// # Returns
///
/// - `Result<SyncSender<WriterCommand>, String>` - Non-blocking sender handle or spawn error.
pub(crate) fn spawn_file_writer(
    file: File,
    capacity: usize,
) -> Result<SyncSender<WriterCommand>, String> {
    let (tx, rx): (SyncSender<WriterCommand>, Receiver<WriterCommand>) =
        sync_channel(capacity.max(1));
    let _: JoinHandle<()> = Builder::new()
        .name(LOGGER_WRITER_THREAD_NAME.to_owned())
        .spawn(move || {
            let mut writer: BufWriter<File> =
                BufWriter::with_capacity(LOGGER_FILE_BUFFER_BYTES, file);
            while let Ok(cmd) = rx.recv() {
                match cmd {
                    WriterCommand::Line(line) => {
                        let _: io::Result<()> = writer.write_all(line.as_bytes());
                        let _: io::Result<()> = writer.write_all(b"\n");
                        while let Ok(next_cmd) = rx.try_recv() {
                            match next_cmd {
                                WriterCommand::Line(next_line) => {
                                    let _: io::Result<()> = writer.write_all(next_line.as_bytes());
                                    let _: io::Result<()> = writer.write_all(b"\n");
                                }
                                WriterCommand::Flush(ack) => {
                                    let _: io::Result<()> = writer.flush();
                                    let _: Result<(), TrySendError<()>> = ack.try_send(());
                                }
                            }
                        }
                        let _: io::Result<()> = writer.flush();
                    }
                    WriterCommand::Flush(ack) => {
                        let _: io::Result<()> = writer.flush();
                        let _: Result<(), TrySendError<()>> = ack.try_send(());
                    }
                }
            }
            let _: io::Result<()> = writer.flush();
        })
        .map_err(|err: io::Error| format!("failed to spawn logger writer thread: {err}"))?;
    Ok(tx)
}