From 8debf1e2751cccd679682eb5005f15f2f66343a6 Mon Sep 17 00:00:00 2001 From: Ed Page Date: Tue, 1 Apr 2025 12:49:58 -0500 Subject: [PATCH] feat(fmt)!: Generalize custom formatter to 'RecordFormat' This breaks type inference for basic custom formatters --- src/fmt/mod.rs | 13 ++++++++++++- src/logger.rs | 6 ++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/fmt/mod.rs b/src/fmt/mod.rs index bd2a2b8..fda54e6 100644 --- a/src/fmt/mod.rs +++ b/src/fmt/mod.rs @@ -200,7 +200,18 @@ impl fmt::Debug for Formatter { } } -pub(crate) trait RecordFormat { +/// Formats a log [`Record`] to be outputted +/// +/// This is called on each record logged and should format the +/// log record and output it to the given [`Formatter`]. +/// +/// This is expected to output the content directly to the +/// [`Formatter`] so that implementations can use the [`std::fmt`] macros +/// to format and output without intermediate heap allocations. +/// +/// When the `color` feature is enabled, styling via ANSI escape codes is supported and the +/// output will automatically respect [`Builder::write_style`]. +pub trait RecordFormat { fn format(&self, formatter: &mut Formatter, record: &Record<'_>) -> io::Result<()>; } diff --git a/src/logger.rs b/src/logger.rs index bd4d13b..82cce29 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -1,4 +1,6 @@ -use std::{borrow::Cow, cell::RefCell, env, io}; +#[cfg(feature = "kv")] +use std::io; +use std::{borrow::Cow, cell::RefCell, env}; use log::{LevelFilter, Log, Metadata, Record, SetLoggerError}; @@ -242,7 +244,7 @@ impl Builder { /// [`std::fmt`]: https://doc.rust-lang.org/std/fmt/index.html pub fn format(&mut self, format: F) -> &mut Self where - F: Fn(&mut Formatter, &Record<'_>) -> io::Result<()> + Sync + Send + 'static, + F: fmt::RecordFormat + Sync + Send + 'static, { self.format.custom_format = Some(Box::new(format)); self