From 3bc17d9aa6d0b3720df9eb2a5d8fa865a26dbc94 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 17:16:44 +0800 Subject: [PATCH 1/4] refactor(append-file)!: redesign rolling file appender with direct segment writes `RollingFileWriter` previously wrote to a single active file and shifted reverse-numbered archives (`.1 -> .2 -> .3`) via `fs::rename` on every rollover. That design performed `O(N)` filesystem renames under the writer mutex, risked sharing violations on Windows when external log collectors held open handles, opened new files without `O_APPEND`, panicked on filename suffix boundary underflows or out-of-range timestamps, truncated millisecond bounds to `usize` on 32-bit targets, and juggled multi-layer `Error` wrappers and stashed `Option` values across rotation and cleanup paths. Redesign `logforth-append-file` around direct-write segment files and flat, single-layer error propagation: - Write directly to segment files opened with `.append(true)` (`[.]` without rotation, `.[.]` for time rotation, and `[.].[.]` with ascending `1..` sequence numbers when `rollover_size` is configured), eliminating `fs::rename` completely. - Check size bounds before writing (`size > 0 && size + len > max_size`) using `NonZeroU64` so segments stay within the configured byte budget while writing oversized single records whole into an empty segment. - Compute period bounds `[start, end)` in `jiff::Timestamp` across configurable `TimeZone` (`FileBuilder::timezone`, defaulting to the system timezone), reusing the active segment across repeated local hours during DST fall-back and avoiding panics or 32-bit truncation. - Validate filename stems and suffixes strictly and match only canonical regular segment files during retention cleanup, counting the active file toward `max_log_files` and never unlinking the active segment even if the wall clock steps backward. - Keep error handling linear and single-layer: if rollover or retention cleanup fails, throttle retries for one second, append the current record to the active segment, and return the underlying leaf `Error` directly. Signed-off-by: tison --- CHANGELOG.md | 1 + Cargo.toml | 1 - appenders/file/Cargo.toml | 1 - appenders/file/src/append.rs | 56 +- appenders/file/src/clock.rs | 59 +- appenders/file/src/lib.rs | 45 +- appenders/file/src/rolling.rs | 1167 +++++++++++---------- appenders/file/src/rotation.rs | 186 +++- appenders/file/tests/global_file_limit.rs | 185 +--- logforth/tests/recursive_logging.rs | 3 +- 10 files changed, 869 insertions(+), 835 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee45319..ca72f38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project will be documented in this file. * Upgrade `jiff` to 1.0. * Redesign `logforth_core::Error` without `anyhow`, boxing its payload and removing `with_context`, `sources`, `from_io_error`, and `from_fmt_error`. * Replace `Trap` and `BestEffortTrap` with `ErrorSink` (`StderrErrorSink` and `BlackHoleErrorSink` under `error`), add `LoggerBuilder::error_sink` and `DispatchBuilder::error_sink` overrides, and remove `FileBuilder::trap`. +* Redesign `logforth-append-file` to write directly to period- and ascending-sequence-named segments (`1, 2, ...` from oldest to newest, replacing reverse-shifted archives and the unnumbered active file when rotating), add `FileBuilder::timezone`, take `NonZeroU64` in `rollover_size`, and count the active segment toward `max_log_files`. ## [0.30.1] 2026-06-03 diff --git a/Cargo.toml b/Cargo.toml index 0277e2b..88ab574 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,7 +70,6 @@ opentelemetry-otlp = { version = "0.33.1", default-features = false } opentelemetry_sdk = { version = "0.33.1", default-features = false } pin-project = { version = "1.1.10" } pollster = { version = "0.4.0" } -rand = { version = "0.10.1" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } tempfile = { version = "3.16" } diff --git a/appenders/file/Cargo.toml b/appenders/file/Cargo.toml index daf17a6..cf513c3 100644 --- a/appenders/file/Cargo.toml +++ b/appenders/file/Cargo.toml @@ -37,7 +37,6 @@ logforth-core = { workspace = true } [dev-dependencies] logforth-layout-json = { workspace = true } -rand = { workspace = true } tempfile = { workspace = true } [lints] diff --git a/appenders/file/src/append.rs b/appenders/file/src/append.rs index 494938f..e5f1bdd 100644 --- a/appenders/file/src/append.rs +++ b/appenders/file/src/append.rs @@ -12,11 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::num::NonZeroU64; use std::num::NonZeroUsize; use std::path::PathBuf; use std::sync::Mutex; use std::sync::MutexGuard; +use jiff::tz::TimeZone; use logforth_core::Diagnostic; use logforth_core::Error; use logforth_core::Layout; @@ -28,7 +30,7 @@ use crate::rolling::RollingFileWriter; use crate::rolling::RollingFileWriterBuilder; use crate::rotation::Rotation; -/// A builder to configure and create an [`File`] appender. +/// Configures the directory, segment names, rotation, and retention of a [`File`] appender. /// /// See the [crate documentation](super) for usage examples. #[derive(Debug)] @@ -38,7 +40,11 @@ pub struct FileBuilder { } impl FileBuilder { - /// Create a new file appender builder. + /// Append to `filename` in `basedir`, creating the directory as needed. Rotation is disabled by + /// default. + /// + /// The filename is used literally. Use `FileBuilder::new(dir, "my_app").filename_suffix("log")` + /// to place the period and sequence before the extension, as in `my_app.2026-11-25.1.log`. pub fn new(basedir: impl Into, filename: impl Into) -> Self { Self { builder: RollingFileWriterBuilder::new(basedir, filename), @@ -50,10 +56,8 @@ impl FileBuilder { /// /// # Errors /// - /// Return an error if either: - /// - /// * The log directory cannot be created. - /// * The configured filename is empty. + /// Returns an error for an invalid filename or suffix, an unrepresentable rotation period, or + /// an I/O failure while preparing the directory or opening the initial file. pub fn build(self) -> Result { let FileBuilder { builder, layout } = self; let writer = builder.build()?; @@ -90,36 +94,51 @@ impl FileBuilder { self } - /// Set the rotation strategy to roll over log files daily at 00:00 in the local time zone. + /// Roll over at the start of each day in the configured timezone. pub fn rollover_daily(mut self) -> Self { self.builder = self.builder.rotation(Rotation::Daily); self } - /// Set the rotation strategy to roll over log files if the current log file exceeds the given - /// size. + /// Set the timezone used for rotation boundaries and segment names. Defaults to the system + /// timezone. + pub fn timezone(mut self, tz: TimeZone) -> Self { + self.builder = self.builder.timezone(tz); + self + } + + /// Roll over before a record would exceed the given size in bytes, including its trailing + /// newline. /// - /// If any time-based rotation strategy is set, the size-based rotation will be checked on the - /// current log file after the time-based rotation check. - pub fn rollover_size(mut self, n: NonZeroUsize) -> Self { + /// A single oversized record is written whole to an empty segment. Sequence numbers increase + /// while the period stays active. On entering another period, numbering starts at 1 and + /// skips existing names. + pub fn rollover_size(mut self, n: NonZeroU64) -> Self { self.builder = self.builder.max_file_size(n); self } - /// Set the filename suffix. + /// Add a suffix after all rotation fields. A single leading dot is stripped and an empty input + /// clears the suffix. pub fn filename_suffix(mut self, suffix: impl Into) -> Self { self.builder = self.builder.filename_suffix(suffix); self } - /// Set the maximum number of log files to keep. + /// Keep at most `n` matching files across all periods, including the active file. + /// + /// With rotation enabled, the oldest inactive segments are pruned at startup and after + /// rollover. By default all segments are retained. pub fn max_log_files(mut self, n: NonZeroUsize) -> Self { self.builder = self.builder.max_log_files(n); self } } -/// An appender that writes log records to rolling files. +/// Appends each formatted record and a newline directly to the active file. +/// +/// If opening the next segment fails, the appender writes the record to the current file and +/// returns the rollover error if the write succeeds. It waits one second before retrying rotation. #[derive(Debug)] pub struct File { writer: Mutex, @@ -150,10 +169,3 @@ impl Append for File { writer.flush() } } - -impl Drop for File { - fn drop(&mut self) { - let writer = self.writer.get_mut().unwrap_or_else(|e| e.into_inner()); - let _ = writer.flush(); - } -} diff --git a/appenders/file/src/clock.rs b/appenders/file/src/clock.rs index 5309b1f..4312565 100644 --- a/appenders/file/src/clock.rs +++ b/appenders/file/src/clock.rs @@ -12,68 +12,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -use jiff::ZonedDateTime; +use jiff::Timestamp; #[derive(Debug)] -pub enum Clock { +pub(crate) enum Clock { DefaultClock, #[cfg(test)] - ManualClock(ManualClock), + ManualClock(Timestamp), } impl Clock { - pub fn now(&self) -> ZonedDateTime { + pub(crate) fn now(&self) -> Timestamp { match self { - Clock::DefaultClock => ZonedDateTime::now(), + Clock::DefaultClock => Timestamp::now(), #[cfg(test)] - Clock::ManualClock(clock) => clock.now(), + Clock::ManualClock(now) => *now, } } - - #[cfg(test)] - pub fn set_now(&mut self, now: ZonedDateTime) { - if let Clock::ManualClock(clock) = self { - clock.set_now(now); - } - } -} - -/// The time could be reset. -#[derive(Debug)] -#[cfg(test)] -pub struct ManualClock { - now: ZonedDateTime, -} - -#[cfg(test)] -impl ManualClock { - pub fn new(now: ZonedDateTime) -> ManualClock { - ManualClock { now } - } - - fn now(&self) -> ZonedDateTime { - self.now.clone() - } - - pub fn set_now(&mut self, now: ZonedDateTime) { - self.now = now; - } -} - -#[cfg(test)] -mod tests { - use std::str::FromStr; - - use super::*; - - #[test] - fn test_manual_clock_adjusting() { - let now = ZonedDateTime::from_str("2024-08-10T17:12:52+08[+08]").unwrap(); - let mut clock = ManualClock { now: now.clone() }; - assert_eq!(clock.now(), now); - - let now = ZonedDateTime::from_str("2024-01-01T12:00:00+08[+08]").unwrap(); - clock.set_now(now.clone()); - assert_eq!(clock.now(), now); - } } diff --git a/appenders/file/src/lib.rs b/appenders/file/src/lib.rs index 9c03e95..22414d5 100644 --- a/appenders/file/src/lib.rs +++ b/appenders/file/src/lib.rs @@ -12,30 +12,63 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Appender for writing log records to single file or rolling files. +//! Append log records directly to a single file or to rotating segments. +//! +//! With `FileBuilder::new(dir, "my_app").filename_suffix("log")`, the filename depends on the +//! rotation policy. +//! +//! | Policy | Example filename | +//! | :-------------- | :--------------------------- | +//! | No rotation | `my_app.log` | +//! | Daily | `my_app.2026-11-25.log` | +//! | Size | `my_app.1.log` | +//! | Hourly and size | `my_app.2026-11-25-17.1.log` | +//! +//! Hourly periods include the hour and minutely periods also include the minute, both with two +//! digits. [`FileBuilder::timezone`] selects the timezone for these periods and defaults to the +//! system timezone. The filename is a literal stem. Passing `"my_app.log"` as the stem puts +//! rotation fields after `.log`. +//! +//! [`FileBuilder::rollover_size`] numbers segments from 1 within each period. Files keep the same +//! name throughout their lifetime. On startup, the highest numbered segment in the current period +//! is reused if it has room. [`FileBuilder::max_log_files`] limits the total number of matching +//! files across all periods, including the active file. //! //! # Example //! -//!``` -//! use logforth_append_file::File; +//! ``` +//! use std::num::NonZeroU64; +//! use std::num::NonZeroUsize; +//! +//! use jiff::tz::TimeZone; //! use logforth_append_file::FileBuilder; //! use logforth_core::record::LevelFilter; //! use logforth_layout_json::JsonLayout; //! -//! let rolling = FileBuilder::new("logs", "app_log") +//! # fn configure(dir: &std::path::Path) -> Result<(), Box> { +//! let rolling = FileBuilder::new(dir, "my_app") +//! .filename_suffix("log") //! .layout(JsonLayout::default()) //! .rollover_daily() -//! .build() -//! .unwrap(); +//! .timezone(TimeZone::UTC) +//! .rollover_size(NonZeroU64::try_from(1024 * 1024)?) +//! .max_log_files(NonZeroUsize::try_from(7)?) +//! .build()?; //! //! let logger = logforth_core::builder() //! .dispatch(|d| d.filter(LevelFilter::All).append(rolling)) //! .build(); +//! # Ok(()) +//! # } +//! # configure(tempfile::tempdir()?.path())?; +//! # Ok::<(), Box>(()) //! ``` #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(missing_docs)] +pub extern crate jiff; + pub use self::append::File; pub use self::append::FileBuilder; diff --git a/appenders/file/src/rolling.rs b/appenders/file/src/rolling.rs index 8fd476d..42cfaac 100644 --- a/appenders/file/src/rolling.rs +++ b/appenders/file/src/rolling.rs @@ -14,703 +14,772 @@ use std::fs; use std::fs::File; -use std::fs::Metadata; use std::fs::OpenOptions; +use std::io; use std::io::Write; +use std::num::NonZeroU64; use std::num::NonZeroUsize; +use std::ops::Range; use std::path::Path; use std::path::PathBuf; -use std::str::FromStr; -use jiff::ZonedDateTime; +use jiff::SignedDuration; +use jiff::Timestamp; use jiff::civil::DateTime; +use jiff::tz::TimeZone; use logforth_core::Error; use crate::clock::Clock; use crate::rotation::Rotation; -/// A writer for rolling files. +const RETRY_COOLDOWN: SignedDuration = SignedDuration::from_secs(1); + #[derive(Debug)] -pub struct RollingFileWriter { - state: State, - writer: File, +pub(crate) struct RollingFileWriter { + files: SegmentFiles, + max_files: Option, + timezone: TimeZone, + clock: Clock, + active: Segment, + period_bounds: Option>, + retry_cooldown: Option>, } impl RollingFileWriter { pub(crate) fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> { - let now = self.state.clock.now(); - let writer = &mut self.writer; - let mut rollover_err = None; - - if self.state.should_rollover_on_date(&now) { - self.state.current_filesize = 0; - self.state.next_date_timestamp = self.state.rotation.next_date_timestamp(&now); - let current = &self.state.this_date_timestamp; - if let Err(err) = self.state.refresh_writer(current, writer) { - rollover_err = Some(err); - } - } - - if self.state.should_rollover_on_size() { - self.state.current_filesize = 0; - if let Err(err) = self.state.refresh_writer(&now, writer) - && rollover_err.is_none() - { - rollover_err = Some(err); - } + let now = self.clock.now(); + if let Err(err) = self.rotate_if_needed(now, buf.len()) { + self.retry_cooldown = Some(retry_window(now)); + self.write_record(buf)?; + return Err(err); } + self.write_record(buf) + } - self.state.this_date_timestamp = now; + fn size_exceeded(&self, buf_len: usize) -> bool { + self.files.max_size.is_some_and(|max| { + self.active.size > 0 && self.active.size.saturating_add(buf_len as u64) > max.get() + }) + } - writer - .write_all(buf) - .map_err(|err| Error::new("failed to write log file").with_source(err))?; - self.state.current_filesize += buf.len(); + fn should_rotate(&self, now: Timestamp, buf_len: usize) -> bool { + if self + .retry_cooldown + .as_ref() + .is_some_and(|window| window.contains(&now)) + { + return false; + } + self.period_bounds + .as_ref() + .is_some_and(|bounds| !bounds.contains(&now)) + || self.size_exceeded(buf_len) + } - if let Some(err) = rollover_err { - return Err(err); + fn rotate_if_needed(&mut self, now: Timestamp, buf_len: usize) -> Result { + if !self.should_rotate(now, buf_len) { + return Ok(false); + } + let period = self.files.rotation.period_at(now, &self.timezone)?; + let key = period.as_ref().map(|p| p.key); + let bounds = period.map(|p| p.bounds); + if key == self.active.name.period && !self.size_exceeded(buf_len) { + self.period_bounds = bounds; + self.retry_cooldown = None; + return Ok(false); } + let segment = if self.files.max_size.is_some() { + let previous = if key == self.active.name.period { + self.active.name.seq + } else { + None + }; + self.files.create_segment(key, previous)? + } else { + let name = SegmentName { + period: key, + seq: None, + }; + Segment::open(self.files.path(name), name, 0)? + }; + self.active = segment; + self.period_bounds = bounds; + self.retry_cooldown = None; + self.prune_if_needed()?; + Ok(true) + } + fn write_record(&mut self, buf: &[u8]) -> Result<(), Error> { + self.active.file.write_all(buf).map_err(|err| { + // A failed write_all may already have appended part of the record. + if let Ok(metadata) = self.active.file.metadata() { + self.active.size = metadata.len(); + } + file_error("write log file", &self.active.path, err) + })?; + self.active.size = self.active.size.saturating_add(buf.len() as u64); Ok(()) } pub(crate) fn flush(&mut self) -> Result<(), Error> { - self.writer + self.active + .file .flush() - .map_err(|err| Error::new("failed to flush log file").with_source(err)) + .map_err(|err| file_error("flush log file", &self.active.path, err)) + } + + fn prune_if_needed(&self) -> Result<(), Error> { + let Some(max_files) = self.max_files else { + return Ok(()); + }; + let mut matching = self.files.list_matching_files()?; + let excess = matching.len().saturating_sub(max_files.get()); + if excess == 0 { + return Ok(()); + } + matching.sort_unstable_by_key(|(name, _)| *name); + for (_, path) in matching + .into_iter() + .filter(|(_, path)| *path != self.active.path) + .take(excess) + { + match fs::remove_file(&path) { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => return Err(file_error("remove old log file", &path, err)), + } + } + Ok(()) } } -/// A builder for configuring [`RollingFileWriter`]. #[derive(Debug)] -pub struct RollingFileWriterBuilder { - // required - basedir: PathBuf, - filename: String, - - // has default - rotation: Rotation, - filename_suffix: Option, - max_size: Option, +pub(crate) struct RollingFileWriterBuilder { + files: SegmentFiles, max_files: Option, + timezone: TimeZone, clock: Clock, } impl RollingFileWriterBuilder { - /// Creates a new [`RollingFileWriterBuilder`]. - #[must_use] - pub fn new(basedir: impl Into, filename: impl Into) -> Self { + pub(crate) fn new(basedir: impl Into, filename: impl Into) -> Self { Self { - basedir: basedir.into(), - filename: filename.into(), - rotation: Rotation::Never, - filename_suffix: None, - max_size: None, + files: SegmentFiles { + basedir: basedir.into(), + filename: filename.into(), + filename_suffix: None, + rotation: Rotation::Never, + max_size: None, + }, max_files: None, + timezone: TimeZone::system(), clock: Clock::DefaultClock, } } - /// Set the rotation policy. - #[must_use] - pub fn rotation(mut self, rotation: Rotation) -> Self { - self.rotation = rotation; + pub(crate) fn rotation(mut self, rotation: Rotation) -> Self { + self.files.rotation = rotation; self } - /// Set the filename suffix. - #[must_use] - pub fn filename_suffix(mut self, suffix: impl Into) -> Self { + pub(crate) fn timezone(mut self, tz: TimeZone) -> Self { + self.timezone = tz; + self + } + + pub(crate) fn filename_suffix(mut self, suffix: impl Into) -> Self { let suffix = suffix.into(); - self.filename_suffix = if suffix.is_empty() { + self.files.filename_suffix = if suffix.is_empty() { None } else { - Some(suffix) + Some(suffix.strip_prefix('.').unwrap_or(&suffix).to_owned()) }; self } - /// Set the maximum number of log files to keep. - #[must_use] - pub fn max_log_files(mut self, n: NonZeroUsize) -> Self { + pub(crate) fn max_log_files(mut self, n: NonZeroUsize) -> Self { self.max_files = Some(n); self } - /// Set the maximum size of a log file in bytes. - #[must_use] - pub fn max_file_size(mut self, n: NonZeroUsize) -> Self { - self.max_size = Some(n); - self - } - - #[cfg(test)] - fn clock(mut self, clock: Clock) -> Self { - self.clock = clock; + pub(crate) fn max_file_size(mut self, n: NonZeroU64) -> Self { + self.files.max_size = Some(n); self } - /// Builds the [`RollingFileWriter`]. - pub fn build(self) -> Result { + pub(crate) fn build(self) -> Result { let Self { - basedir, - rotation, - filename, - filename_suffix, - max_size, + files, max_files, + timezone, clock, } = self; - - if filename.is_empty() { - return Err(Error::new("filename must not be empty")); + validate_component("filename", &files.filename)?; + if let Some(suffix) = &files.filename_suffix { + validate_component("filename suffix", suffix)?; } - - let (state, writer) = State::new( - rotation, - basedir, - filename, - filename_suffix, - max_size, + fs::create_dir_all(&files.basedir) + .map_err(|err| file_error("create log directory", &files.basedir, err))?; + let period = files.rotation.period_at(clock.now(), &timezone)?; + let active = files.open_initial(period.as_ref().map(|p| p.key))?; + let writer = RollingFileWriter { + files, max_files, + timezone, clock, - )?; - - Ok(RollingFileWriter { state, writer }) + active, + period_bounds: period.map(|p| p.bounds), + retry_cooldown: None, + }; + if writer.files.rotation != Rotation::Never || writer.files.max_size.is_some() { + // Startup cleanup is best-effort so locked historical files never block initialization. + let _ = writer.prune_if_needed(); + } + Ok(writer) } } -#[derive(Debug)] -struct LogFile { - filepath: PathBuf, - metadata: Metadata, - datetime: DateTime, - count: usize, +fn retry_window(now: Timestamp) -> Range { + now..now.checked_add(RETRY_COOLDOWN).unwrap_or(Timestamp::MAX) } -// oldest is the least -fn compare_logfile(a: &LogFile, b: &LogFile) -> std::cmp::Ordering { - match a.datetime.cmp(&b.datetime) { - std::cmp::Ordering::Equal => { - let a_rev = usize::MAX - a.count; - let b_rev = usize::MAX - b.count; - a_rev.cmp(&b_rev) - } - ord => ord, +fn validate_component(label: &str, value: &str) -> Result<(), Error> { + if value.contains(['/', '\\', '\0']) || Path::new(value).file_name() != Some(value.as_ref()) { + return Err(Error::new(format!("invalid {label}: {value:?}"))); } + Ok(()) } -#[derive(Debug)] -struct State { - log_dir: PathBuf, - log_filename: String, - log_filename_suffix: Option, - date_format: &'static str, - rotation: Rotation, - current_filesize: usize, - this_date_timestamp: ZonedDateTime, - next_date_timestamp: Option, - max_size: Option, - max_files: Option, - clock: Clock, +fn file_error(operation: &str, path: &Path, err: io::Error) -> Error { + Error::new(format!("failed to {operation}: {}", path.display())).with_source(err) } -impl State { - fn new( - rotation: Rotation, - dir: impl AsRef, - log_filename: String, - log_filename_suffix: Option, - max_size: Option, - max_files: Option, - clock: Clock, - ) -> Result<(Self, File), Error> { - let now = clock.now(); - let log_dir = dir.as_ref().to_path_buf(); - fs::create_dir_all(&log_dir) - .map_err(|err| Error::new("failed to create log directory").with_source(err))?; - - let mut state = State { - log_dir, - log_filename, - log_filename_suffix, - date_format: rotation.date_format(), - current_filesize: 0, - this_date_timestamp: clock.now(), - next_date_timestamp: rotation.next_date_timestamp(&now), - rotation, - max_size, - max_files, - clock, - }; - - let files = { - let mut files = state.list_logfiles()?; - files.sort_by(compare_logfile); - files - }; +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +struct SegmentName { + period: Option, + seq: Option, +} - let file = match files.last() { - None => { - // brand-new directory - state.create_log_writer()? - } - Some(last) => { - let filename = state.current_filename(); - if last.filepath != filename { - // for some reason, the `filename.suffix` file does not exist; create a new one - state.create_log_writer()? - } else { - state.current_filesize = last.metadata.len() as usize; - - if let Ok(mtime) = last.metadata.modified() - && let Ok(mtime) = ZonedDateTime::try_from(mtime) - { - state.next_date_timestamp = state.rotation.next_date_timestamp(&mtime); - state.this_date_timestamp = mtime; - } - - // continue to use the existing current log file - OpenOptions::new() - .append(true) - .open(&filename) - .map_err(|err| Error::new("failed to open current log").with_source(err))? - } - } - }; +#[derive(Debug)] +struct Segment { + name: SegmentName, + path: PathBuf, + file: File, + size: u64, +} - Ok((state, file)) +impl Segment { + fn open(path: PathBuf, name: SegmentName, size: u64) -> Result { + let file = OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .map_err(|err| file_error("open log file", &path, err))?; + Ok(Self { + name, + path, + file, + size, + }) } +} + +#[derive(Debug)] +struct SegmentFiles { + basedir: PathBuf, + filename: String, + filename_suffix: Option, + rotation: Rotation, + max_size: Option, +} - fn current_filename(&self) -> PathBuf { - let filename = &self.log_filename; - match self.log_filename_suffix.as_ref() { - None => self.log_dir.join(filename), - Some(suffix) => self.log_dir.join(format!("{filename}.{suffix}")), +impl SegmentFiles { + fn path(&self, name: SegmentName) -> PathBuf { + let mut filename = self.filename.clone(); + if let Some(period) = name.period { + filename.push('.'); + filename.push_str(&period.strftime(self.rotation.date_format()).to_string()); } + if let Some(seq) = name.seq { + filename.push('.'); + filename.push_str(&seq.to_string()); + } + if let Some(suffix) = &self.filename_suffix { + filename.push('.'); + filename.push_str(suffix); + } + self.basedir.join(filename) } - fn create_log_writer(&self) -> Result { - let filename = self.current_filename(); - OpenOptions::new() - .write(true) - .create_new(true) - .open(&filename) - .map_err(|err| Error::new("failed to create log file").with_source(err)) - } - - fn join_date(&self, date: &ZonedDateTime, cnt: usize) -> PathBuf { - let date = date.strftime(self.date_format); - let filename = match ( - &self.rotation, - &self.log_filename, - &self.log_filename_suffix, - ) { - (&Rotation::Never, filename, None) => format!("{filename}.{cnt}"), - (&Rotation::Never, filename, Some(suffix)) => { - format!("{filename}.{cnt}.{suffix}") - } - (_, filename, Some(suffix)) => format!("{filename}.{date}.{cnt}.{suffix}"), - (_, filename, None) => format!("{filename}.{date}.{cnt}"), + fn open_initial(&self, period: Option) -> Result { + let Some(max) = self.max_size else { + let name = SegmentName { period, seq: None }; + return Segment::open(self.path(name), name, 0); }; - self.log_dir.join(filename) + let highest = self + .list_matching_files()? + .into_iter() + .filter(|(name, _)| name.period == period) + .max_by_key(|(name, _)| name.seq); + let mut previous = None; + if let Some((name, path)) = highest { + let size = fs::metadata(&path) + .map_err(|err| file_error("read log file metadata", &path, err))? + .len(); + if size < max.get() { + return Segment::open(path, name, size); + } + previous = name.seq; + } + self.create_segment(period, previous) } - fn list_logfiles(&self) -> Result, Error> { - let read_dir = fs::read_dir(&self.log_dir).map_err(|err| { - Error::new(format!( - "failed to read log dir: {}", - self.log_dir.display() - )) - .with_source(err) - })?; - - let files = read_dir - .filter_map(|entry| { - let entry = entry.ok()?; - let filepath = entry.path(); - - let metadata = entry.metadata().ok()?; - // the appender only creates files, not directories or symlinks, - if !metadata.is_file() { - return None; - } - - let filename = entry.file_name(); - // if the filename is not a UTF-8 string, skip it. - let mut filename = filename.to_str()?; - if !filename.starts_with(&self.log_filename) { - return None; - } - filename = &filename[self.log_filename.len()..]; - - if let Some(suffix) = &self.log_filename_suffix { - if !filename.ends_with(suffix) { - return None; - } - filename = &filename[..filename.len() - suffix.len() - 1]; - } - - if filename.is_empty() { - // the current log file is the largest - return Some(LogFile { - filepath, - metadata, - datetime: DateTime::MAX, - count: 0, + fn create_segment( + &self, + period: Option, + previous: Option, + ) -> Result { + let mut seq = previous.map_or(NonZeroU64::MIN, |seq| seq.saturating_add(1)); + loop { + let name = SegmentName { + period, + seq: Some(seq), + }; + let path = self.path(name); + match OpenOptions::new().create_new(true).append(true).open(&path) { + Ok(file) => { + return Ok(Segment { + name, + path, + file, + size: 0, }); } - - if filename.starts_with(".") { - filename = &filename[1..]; - } else { - return None; + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { + seq = seq + .checked_add(1) + .ok_or_else(|| file_error("allocate log file sequence", &path, err))?; } - - let datetime = if self.rotation != Rotation::Never { - // mandatory datetime part - let pos = filename.find('.')?; - let datetime = DateTime::strptime(self.date_format, &filename[..pos]).ok()?; - filename = &filename[pos + 1..]; - datetime - } else { - DateTime::MAX - }; - - let count = usize::from_str(&filename[..filename.len()]).ok()?; - - Some(LogFile { - filepath, - metadata, - datetime, - count, - }) - }) - .collect::>(); - - Ok(files) - } - - fn delete_oldest_logs(&self, max_files: usize) -> Result<(), Error> { - let mut files = self.list_logfiles()?; - if files.len() < max_files { - return Ok(()); - } - - // delete files, so that (n-1) files remain, because we will create another log file - files.sort_by(compare_logfile); - for file in files.iter().take(files.len() - (max_files - 1)) { - let filepath = &file.filepath; - fs::remove_file(filepath).map_err(|err| { - Error::new(format!("failed to remove old log: {}", filepath.display())) - .with_source(err) - })?; + Err(err) => return Err(file_error("create log file", &path, err)), + } } - - Ok(()) } - fn rotate_log_writer(&self, now: &ZonedDateTime) -> Result<(File, Option), Error> { - let mut renames = vec![]; - for i in 1..self.max_files.map_or(usize::MAX, |n| n.get()) { - let filepath = self.join_date(now, i); - if fs::exists(&filepath).is_ok_and(|ok| ok) { - let next = self.join_date(now, i + 1); - renames.push((filepath, next)); - } else { - break; + fn list_matching_files(&self) -> Result, Error> { + let read_error = |err| file_error("read log directory", &self.basedir, err); + let mut files = Vec::new(); + for entry in fs::read_dir(&self.basedir).map_err(read_error)? { + let entry = entry.map_err(read_error)?; + if let Some(name) = self.parse_segment_filename(&entry) { + files.push((name, entry.path())); } } + Ok(files) + } - for (old, new) in renames.iter().rev() { - fs::rename(old, new).map_err(|err| { - Error::new(format!("failed to rotate log: {}", old.display())).with_source(err) - })? + fn parse_segment_filename(&self, entry: &fs::DirEntry) -> Option { + if !entry.file_type().ok()?.is_file() { + return None; } - - let archive_filepath = self.join_date(now, 1); - let current_filepath = self.current_filename(); - fs::rename(¤t_filepath, &archive_filepath).map_err(|err| { - Error::new(format!( - "failed to archive log: {}", - current_filepath.display() - )) - .with_source(err) - })?; - - let cleanup_err = if let Some(max_files) = self.max_files { - self.delete_oldest_logs(max_files.get()) - .err() - .map(|err| Error::new("failed to delete oldest logs").with_source(err)) - } else { - None + let file_name = entry.file_name(); + let rest = file_name + .to_str()? + .strip_prefix(&self.filename)? + .strip_prefix('.')?; + let middle = match &self.filename_suffix { + Some(suffix) => rest.strip_suffix(suffix.as_str())?.strip_suffix('.')?, + None => rest, }; - - let new_file = self.create_log_writer()?; - Ok((new_file, cleanup_err)) - } - - fn refresh_writer(&self, now: &ZonedDateTime, file: &mut File) -> Result<(), Error> { - match self.rotate_log_writer(now) { - Ok((new_file, cleanup_err)) => { - let flush_err = file - .flush() - .err() - .map(|err| Error::new("failed to flush previous writer").with_source(err)); - *file = new_file; - if let Some(err) = cleanup_err.or(flush_err) { - return Err(err); - } - Ok(()) + let (period, seq) = match (self.rotation, self.max_size.is_some()) { + (Rotation::Never, false) => return None, + (Rotation::Never, true) => (None, Some(parse_seq(middle)?)), + (rotation, false) => (Some(rotation.parse_period(middle)?), None), + (rotation, true) => { + let (period, seq) = middle.split_once('.')?; + (Some(rotation.parse_period(period)?), Some(parse_seq(seq)?)) } - Err(err) => Err(Error::new("failed to rotate log writer").with_source(err)), - } - } - - fn should_rollover_on_date(&self, date: &ZonedDateTime) -> bool { - self.next_date_timestamp - .is_some_and(|ts| date.timestamp().as_millisecond() as usize >= ts) + }; + Some(SegmentName { period, seq }) } +} - fn should_rollover_on_size(&self) -> bool { - self.max_size - .is_some_and(|n| self.current_filesize >= n.get()) +fn parse_seq(s: &str) -> Option { + if s.is_empty() || s.starts_with('0') || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; } + s.parse().ok() } #[cfg(test)] mod tests { - use std::cmp::min; - use std::fs; - use std::num::NonZeroUsize; - use std::ops::Add; - use std::str::FromStr; - - use jiff::Span; - use jiff::ZonedDateTime; - use rand::RngExt; - use rand::distr::Alphanumeric; + use std::error::Error as _; + use tempfile::TempDir; + use tempfile::tempdir; - use crate::clock::Clock; - use crate::clock::ManualClock; - use crate::rolling::RollingFileWriterBuilder; - use crate::rotation::Rotation; + use super::*; + + fn builder(dir: &TempDir, rotation: Rotation, now: &str) -> RollingFileWriterBuilder { + let mut builder = RollingFileWriterBuilder::new(dir.path(), "my_app") + .rotation(rotation) + .timezone(TimeZone::UTC) + .filename_suffix(".log"); + builder.clock = Clock::ManualClock(now.parse().unwrap()); + builder + } #[test] - fn test_file_rolling_via_file_size() { - test_file_rolling_for_specific_file_size(3, 1000); - test_file_rolling_for_specific_file_size(3, 10000); - test_file_rolling_for_specific_file_size(10, 8888); - test_file_rolling_for_specific_file_size(10, 10000); - test_file_rolling_for_specific_file_size(20, 6666); - test_file_rolling_for_specific_file_size(20, 10000); - } - - fn test_file_rolling_for_specific_file_size(max_files: usize, max_size: usize) { - let max_files = NonZeroUsize::new(max_files).unwrap(); - let max_size = NonZeroUsize::new(max_size).unwrap(); - let temp_dir = TempDir::new().unwrap(); - - let mut writer = RollingFileWriterBuilder::new(temp_dir.as_ref(), "test_file") - .rotation(Rotation::Never) + fn validates_names_before_creating_the_directory() { + let dir = tempdir().unwrap(); + let path = dir.path().join("new"); + for stem in ["", ".", "..", "/logs", "a/b", "a\\b", "a\0b"] { + assert!( + RollingFileWriterBuilder::new(&path, stem).build().is_err(), + "{stem:?}" + ); + } + for suffix in [".", "..", "...", "a/b", "a\\b", "a\0b"] { + assert!( + RollingFileWriterBuilder::new(&path, "app") + .filename_suffix(suffix) + .build() + .is_err(), + "{suffix:?}" + ); + } + assert!(!path.exists()); + #[cfg(windows)] + assert!(validate_component("filename", "C:relative").is_err()); + + for (suffix, name) in [("", "app"), (".log", "app.log"), ("..log", "app..log")] { + let mut writer = RollingFileWriterBuilder::new(&path, "app") + .filename_suffix(suffix) + .build() + .unwrap(); + writer.write_all(b"record").unwrap(); + assert_eq!(fs::read(path.join(name)).unwrap(), b"record"); + } + } + + #[test] + fn size_retention_only_deletes_canonical_regular_files() { + let dir = tempdir().unwrap(); + let unrelated = [ + "my_applog", + "my_appXlog", + "my_app2.log", + "my_app.01.log", + "my_app.log", + "my_app.0.log", + "my_app.+1.log", + "my_app.18446744073709551616.log", + "my_app.1log", + "my_app.2026-11-25.log", + "my_app.2026-11-25.1.log", + ]; + for name in unrelated { + fs::write(dir.path().join(name), b"keep").unwrap(); + } + fs::create_dir(dir.path().join("my_app.3.log")).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink("my_app.log", dir.path().join("my_app.4.log")).unwrap(); + for seq in [1, 2, 10] { + fs::write(dir.path().join(format!("my_app.{seq}.log")), b"full").unwrap(); + } + let mut writer = RollingFileWriterBuilder::new(dir.path(), "my_app") .filename_suffix("log") - .max_log_files(max_files) - .max_file_size(max_size) + .max_file_size(NonZeroU64::MIN) + .max_log_files(NonZeroUsize::MIN) .build() .unwrap(); + writer.write_all(b"new").unwrap(); + assert_eq!(fs::read(dir.path().join("my_app.11.log")).unwrap(), b"new"); + for seq in [1, 2, 10] { + assert!(!dir.path().join(format!("my_app.{seq}.log")).exists()); + } + for name in unrelated { + assert_eq!(fs::read(dir.path().join(name)).unwrap(), b"keep", "{name}"); + } + assert!(dir.path().join("my_app.3.log").is_dir()); + #[cfg(unix)] + assert!(dir.path().join("my_app.4.log").is_symlink()); + } - for i in 1..=(max_files.get() * 2) { - let mut expected_file_size = 0; - while expected_file_size < max_size.get() { - let rand_str = generate_random_string(); - expected_file_size += rand_str.len(); - writer.write_all(rand_str.as_bytes()).unwrap(); - assert_eq!(writer.state.current_filesize, expected_file_size); + #[test] + fn time_retention_recognizes_only_the_configured_period_format() { + for (rotation, valid, invalid) in [ + ( + Rotation::Daily, + "2024-02-29", + ["2023-02-29", "+024-02-29", "2024-02-29-03"], + ), + ( + Rotation::Hourly, + "2024-02-29-23", + ["2024-02-29-24", "2024-02-29- 3", "2024-02-29"], + ), + ( + Rotation::Minutely, + "2024-02-29-23-59", + ["2024-02-29-23-60", "2024-02-29-23- 9", "2024-02-29-23"], + ), + ] { + let dir = tempdir().unwrap(); + for period in [valid, invalid[0], invalid[1], invalid[2]] { + fs::write(dir.path().join(format!("my_app.{period}.log")), b"old").unwrap(); + } + let mut writer = builder(&dir, rotation, "2026-11-25T01:02:03Z") + .max_log_files(NonZeroUsize::MIN) + .build() + .unwrap(); + writer.write_all(b"new").unwrap(); + assert!(!dir.path().join(format!("my_app.{valid}.log")).exists()); + for period in invalid { + assert!(dir.path().join(format!("my_app.{period}.log")).exists()); } + } + } - writer.flush().unwrap(); + #[test] + fn checks_size_before_writing_and_keeps_oversized_records_whole() { + let dir = tempdir().unwrap(); + let mut writer = RollingFileWriterBuilder::new(dir.path(), "app") + .max_file_size(NonZeroU64::new(5).unwrap()) + .build() + .unwrap(); + for record in [ + b"oversized".as_slice(), + b"abc", + b"de", + b"1234", + b"xy", + b"another oversized", + ] { + writer.write_all(record).unwrap(); + } + let expected = [ + b"oversized".as_slice(), + b"abcde", + b"1234", + b"xy", + b"another oversized", + ]; + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), expected.len()); + for (i, contents) in expected.into_iter().enumerate() { assert_eq!( - fs::read_dir(&writer.state.log_dir).unwrap().count(), - min(i, max_files.get()) + fs::read(dir.path().join(format!("app.{}", i + 1))).unwrap(), + contents ); } } #[test] - fn test_file_rolling_via_time_rotation() { - test_file_rolling_for_specific_time_rotation( - Rotation::Minutely, - Span::new().minutes(1), - Span::new().seconds(1), + fn restart_resumes_only_the_highest_segment_in_the_current_period() { + let dir = tempdir().unwrap(); + let build = || { + builder(&dir, Rotation::Hourly, "2026-11-25T17:01:00Z") + .max_file_size(NonZeroU64::new(5).unwrap()) + .build() + .unwrap() + }; + let current = dir.path().join("my_app.2026-11-25-17.10.log"); + let future = dir.path().join("my_app.2026-11-25-18.99.log"); + fs::write(dir.path().join("my_app.2026-11-25-17.9.log"), b"old").unwrap(); + fs::write(¤t, b"ab").unwrap(); + fs::write(&future, b"future").unwrap(); + + build().write_all(b"cde").unwrap(); + assert_eq!(fs::read(¤t).unwrap(), b"abcde"); + let mut writer = build(); + assert!(dir.path().join("my_app.2026-11-25-17.11.log").is_file()); + writer.write_all(b"oversized").unwrap(); + drop(writer); + build().write_all(b"new").unwrap(); + assert_eq!( + fs::read(dir.path().join("my_app.2026-11-25-17.12.log")).unwrap(), + b"new" ); - test_file_rolling_for_specific_time_rotation( - Rotation::Hourly, - Span::new().hours(1), - Span::new().minutes(1), + assert_eq!(fs::read(future).unwrap(), b"future"); + build().write_all(b"123").unwrap(); + assert_eq!( + fs::read(dir.path().join("my_app.2026-11-25-17.12.log")).unwrap(), + b"new" ); - test_file_rolling_for_specific_time_rotation( - Rotation::Daily, - Span::new().days(1), - Span::new().hours(1), + assert_eq!( + fs::read(dir.path().join("my_app.2026-11-25-17.13.log")).unwrap(), + b"123" ); } - fn test_file_rolling_for_specific_time_rotation( - rotation: Rotation, - rotation_duration: Span, - write_interval: Span, - ) { - let max_files = NonZeroUsize::new(10).unwrap(); - let temp_dir = TempDir::new().unwrap(); + #[test] + fn sequence_exhaustion_preserves_the_full_segment() { + let dir = tempdir().unwrap(); + let path = dir.path().join(format!("my_app.{}", u64::MAX)); + fs::write(&path, b"x").unwrap(); + let err = RollingFileWriterBuilder::new(dir.path(), "my_app") + .max_file_size(NonZeroU64::MIN) + .build() + .unwrap_err(); + assert_eq!( + err.source() + .unwrap() + .downcast_ref::() + .unwrap() + .kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!(fs::read(path).unwrap(), b"x"); + } - let start_time = ZonedDateTime::from_str("2024-08-10T00:00:00[UTC]").unwrap(); - let mut writer = RollingFileWriterBuilder::new(temp_dir.as_ref(), "test_file") - .rotation(rotation) - .filename_suffix("log") - .max_log_files(max_files) - .clock(Clock::ManualClock(ManualClock::new(start_time.clone()))) + #[test] + fn collision_on_return_to_a_period_preserves_existing_segments() { + let dir = tempdir().unwrap(); + let mut writer = builder(&dir, Rotation::Hourly, "1969-12-31T23:59:59Z") + .max_file_size(NonZeroU64::MIN) .build() .unwrap(); + writer.write_all(b"a").unwrap(); + writer.write_all(b"b").unwrap(); + writer.clock = Clock::ManualClock("1970-01-01T00:00:00Z".parse().unwrap()); + writer.write_all(b"c").unwrap(); + writer.clock = Clock::ManualClock("1969-12-31T23:59:00Z".parse().unwrap()); + writer.write_all(b"d").unwrap(); + for (name, contents) in [ + ("my_app.1969-12-31-23.1.log", b"a"), + ("my_app.1969-12-31-23.2.log", b"b"), + ("my_app.1970-01-01-00.1.log", b"c"), + ("my_app.1969-12-31-23.3.log", b"d"), + ] { + assert_eq!(fs::read(dir.path().join(name)).unwrap(), contents); + } + } - let mut cur_time = start_time; - - for i in 1..=(max_files.get() * 2) { - let mut expected_file_size = 0; - let end_time = &cur_time + rotation_duration; - while cur_time < end_time { - writer.state.clock.set_now(cur_time.clone()); - - let rand_str = generate_random_string(); - expected_file_size += rand_str.len(); - - writer.write_all(rand_str.as_bytes()).unwrap(); - assert_eq!(writer.state.current_filesize, expected_file_size); + #[test] + fn pruning_keeps_the_active_file_when_the_clock_moves_back() { + let dir = tempdir().unwrap(); + let future = dir.path().join("my_app.2026-11-27.log"); + let today = dir.path().join("my_app.2026-11-26.log"); + let past = dir.path().join("my_app.2026-11-25.log"); + fs::write(&future, b"future").unwrap(); + let mut writer = builder(&dir, Rotation::Daily, "2026-11-26T05:00:00Z") + .max_log_files(NonZeroUsize::MIN) + .build() + .unwrap(); + writer.write_all(b"today").unwrap(); + assert!(!future.exists()); + assert_eq!(fs::read(&today).unwrap(), b"today"); + + fs::write(&past, b"existing ").unwrap(); + writer.clock = Clock::ManualClock("2026-11-25T05:00:00Z".parse().unwrap()); + writer.write_all(b"past").unwrap(); + assert_eq!(fs::read(past).unwrap(), b"existing past"); + assert!(!today.exists()); + } - cur_time = cur_time.add(write_interval); + #[test] + fn fall_back_reuses_the_local_hour_then_rotates_at_its_second_end() { + for max_size in [None, NonZeroU64::new(100)] { + let dir = tempdir().unwrap(); + let mut b = builder(&dir, Rotation::Hourly, "2026-11-01T01:00:00-04:00") + .timezone(TimeZone::get("America/New_York").unwrap()); + if let Some(max) = max_size { + b = b.max_file_size(max); } - - writer.flush().unwrap(); - assert_eq!( - fs::read_dir(&writer.state.log_dir).unwrap().count(), - min(i, max_files.get()) - ); + let mut writer = b.build().unwrap(); + writer.write_all(b"EDT ").unwrap(); + writer.clock = Clock::ManualClock("2026-11-01T01:00:00-05:00".parse().unwrap()); + assert!(writer.should_rotate(writer.clock.now(), 3)); + assert!(!writer.rotate_if_needed(writer.clock.now(), 3).unwrap()); + writer.write_all(b"EST").unwrap(); + writer.clock = Clock::ManualClock("2026-11-01T02:00:00-05:00".parse().unwrap()); + writer.write_all(b"later").unwrap(); + + let (first, second) = if max_size.is_some() { + ("my_app.2026-11-01-01.1.log", "my_app.2026-11-01-02.1.log") + } else { + ("my_app.2026-11-01-01.log", "my_app.2026-11-01-02.log") + }; + assert_eq!(fs::read(dir.path().join(first)).unwrap(), b"EDT EST"); + assert_eq!(fs::read(dir.path().join(second)).unwrap(), b"later"); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); } } + #[cfg(unix)] #[test] - fn test_file_rolling_via_file_size_and_time_rotation() { - test_file_size_and_time_rotation_for_specific_time_rotation( - Rotation::Minutely, - Span::new().minutes(1), - Span::new().seconds(1), - ); - test_file_size_and_time_rotation_for_specific_time_rotation( - Rotation::Hourly, - Span::new().hours(1), - Span::new().minutes(1), - ); - test_file_size_and_time_rotation_for_specific_time_rotation( - Rotation::Daily, - Span::new().days(1), - Span::new().hours(1), - ); - } + fn failed_rollover_appends_the_record_and_waits_one_second_before_retrying() { + use std::os::unix::fs::PermissionsExt; - fn test_file_size_and_time_rotation_for_specific_time_rotation( - rotation: Rotation, - rotation_duration: Span, - write_interval: Span, - ) { - let max_files = NonZeroUsize::new(10).unwrap(); - let file_size = NonZeroUsize::new(500).unwrap(); - // Small file size and too many files to ensure both of file size and time rotation can be - // triggered. - let total_files = 100; - let temp_dir = TempDir::new().unwrap(); - - let start_time = ZonedDateTime::from_str("2024-08-10T00:00:00[UTC]").unwrap(); - let mut writer = RollingFileWriterBuilder::new(temp_dir.as_ref(), "test_file") - .rotation(rotation) - .filename_suffix("log") - .max_log_files(max_files) - .max_file_size(file_size) - .clock(Clock::ManualClock(ManualClock::new(start_time.clone()))) + let dir = tempdir().unwrap(); + let mut writer = builder(&dir, Rotation::Minutely, "2026-11-25T17:00:59Z") .build() .unwrap(); - - let mut cur_time = start_time; - let mut end_time = &cur_time + rotation_duration; - let mut time_rotation_trigger = false; - let mut file_size_rotation_trigger = false; - - for i in 1..=total_files { - let mut expected_file_size = 0; - loop { - writer.state.clock.set_now(cur_time.clone()); - - let rand_str = generate_random_string(); - expected_file_size += rand_str.len(); - - writer.write_all(rand_str.as_bytes()).unwrap(); - assert_eq!(writer.state.current_filesize, expected_file_size); - - cur_time += write_interval; - - if cur_time >= end_time { - end_time = end_time.add(rotation_duration); - time_rotation_trigger = true; - break; - } - if expected_file_size >= file_size.get() { - file_size_rotation_trigger = true; - break; - } + let current = dir.path().join("my_app.2026-11-25-17-00.log"); + let next = dir.path().join("my_app.2026-11-25-17-01.log"); + writer.write_all(b"first ").unwrap(); + + let permissions = fs::metadata(dir.path()).unwrap().permissions(); + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap(); + // Privileged test runners can still create files here. In that case the directory + // at the candidate path prevents opening it for append. + let blocker = fs::create_dir(&next); + writer.clock = Clock::ManualClock("2026-11-25T17:01:00Z".parse().unwrap()); + let result = writer.write_all(b"failed "); + fs::set_permissions(dir.path(), permissions).unwrap(); + let err = result.unwrap_err(); + let cause = err.source().unwrap().downcast_ref::().unwrap(); + match blocker { + Ok(()) => fs::remove_dir(&next).unwrap(), + Err(e) => { + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); + assert_eq!(cause.kind(), io::ErrorKind::PermissionDenied); } - - writer.flush().unwrap(); - assert_eq!( - fs::read_dir(&writer.state.log_dir).unwrap().count(), - min(i, max_files.get()) - ); } - assert!(file_size_rotation_trigger); - assert!(time_rotation_trigger); + assert_eq!(fs::read(¤t).unwrap(), b"first failed "); + + writer.clock = Clock::ManualClock("2026-11-25T17:01:00.999Z".parse().unwrap()); + writer.write_all(b"cooldown").unwrap(); + assert!(!next.exists()); + // Stepping the wall clock backward before the failure timestamp exits cooldown immediately. + writer.clock = Clock::ManualClock("2026-11-25T16:59:00Z".parse().unwrap()); + assert!(writer.should_rotate(writer.clock.now(), 1)); + writer.clock = Clock::ManualClock("2026-11-25T17:01:01Z".parse().unwrap()); + writer.write_all(b"retried").unwrap(); + assert_eq!(fs::read(current).unwrap(), b"first failed cooldown"); + assert_eq!(fs::read(next).unwrap(), b"retried"); } #[test] - fn test_rollover_failure_preserves_record_and_returns_error() { - let temp_dir = TempDir::new().unwrap(); - let mut writer = RollingFileWriterBuilder::new(temp_dir.as_ref(), "test_file") - .filename_suffix("log") - .max_file_size(NonZeroUsize::new(5).unwrap()) - .max_log_files(NonZeroUsize::new(2).unwrap()) + fn timestamp_overflow_reports_the_calendar_error_after_writing() { + let dir = tempdir().unwrap(); + let mut writer = builder(&dir, Rotation::Daily, "2026-11-25T00:00:00Z") .build() .unwrap(); - - writer.write_all(b"first\n").unwrap(); - - // Block rotating regular file `test_file.1.log` -> directory `test_file.2.log`. - fs::write(temp_dir.path().join("test_file.1.log"), b"archive").unwrap(); - fs::create_dir_all(temp_dir.path().join("test_file.2.log")).unwrap(); - - let err = writer.write_all(b"second\n").unwrap_err(); - assert!(err.to_string().contains("failed to rotate log writer")); - - writer.flush().unwrap(); - let content = fs::read_to_string(temp_dir.path().join("test_file.log")).unwrap(); - assert_eq!(content, "first\nsecond\n"); + writer.clock = Clock::ManualClock(Timestamp::MAX); + let error = writer.write_all(b"still here").unwrap_err(); + assert!(error.source().unwrap().is::()); + assert_eq!( + fs::read(dir.path().join("my_app.2026-11-25.log")).unwrap(), + b"still here" + ); } - fn generate_random_string() -> String { - let mut rng = rand::rng(); - let len = rng.random_range(50..=100); - let random_string: String = std::iter::repeat(()) - .map(|()| rng.sample(Alphanumeric)) - .map(char::from) - .take(len) - .collect(); - - random_string + #[test] + fn append_after_external_truncation_starts_at_the_new_end() { + let dir = tempdir().unwrap(); + for size in [None, NonZeroU64::new(100)] { + let mut builder = RollingFileWriterBuilder::new(dir.path(), "typed.log"); + builder.files.max_size = size; + let mut writer = builder.build().unwrap(); + let path = dir.path().join(if size.is_some() { + "typed.log.1" + } else { + "typed.log" + }); + writer.write_all(b"original record").unwrap(); + fs::write(&path, b"x").unwrap(); + writer.write_all(b"y").unwrap(); + assert_eq!(fs::read(path).unwrap(), b"xy"); + } } } diff --git a/appenders/file/src/rotation.rs b/appenders/file/src/rotation.rs index 24485f1..ee5b3f2 100644 --- a/appenders/file/src/rotation.rs +++ b/appenders/file/src/rotation.rs @@ -12,82 +12,166 @@ // See the License for the specific language governing permissions and // limitations under the License. -use jiff::RoundMode; +use std::ops::Range; + +use jiff::SignedDuration; +use jiff::Timestamp; use jiff::ToSpan; -use jiff::Unit; -use jiff::ZonedDateTime; -use jiff::ZonedDateTimeRound; +use jiff::civil::DateTime; +use jiff::tz::TimeZone; +use logforth_core::Error; -/// Rotation policies for rolling files. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Rotation { - /// Rotate files every minute. +pub(crate) enum Rotation { Minutely, - /// Rotate files every hour. Hourly, - /// Rotate files every day. Daily, - /// Never rotate files. Never, } +#[derive(Debug)] +pub(crate) struct Period { + pub(crate) key: DateTime, + pub(crate) bounds: Range, +} + impl Rotation { - /// Get the next date timestamp based on the current date and rotation policy. - pub fn next_date_timestamp(&self, current_date: &ZonedDateTime) -> Option { - let round = ZonedDateTimeRound::new().mode(RoundMode::Trunc); - let next_date = match *self { - Rotation::Never => return None, - Rotation::Minutely => (current_date + 1.minute()).round(round.smallest(Unit::Minute)), - Rotation::Hourly => (current_date + 1.hour()).round(round.smallest(Unit::Hour)), - Rotation::Daily => (current_date + 1.day()).round(round.smallest(Unit::Day)), + pub(crate) fn period_at(self, now: Timestamp, tz: &TimeZone) -> Result, Error> { + let local = tz.to_datetime(now); + let (key, span) = match self { + Self::Never => return Ok(None), + Self::Daily => (local.start_of_day(), 1.day()), + Self::Hourly => (local.date().at(local.hour(), 0, 0, 0), 1.hour()), + Self::Minutely => ( + local.date().at(local.hour(), local.minute(), 0, 0), + 1.minute(), + ), }; - let next_date = - next_date.expect("invalid time; this is a bug in logforth rolling file appender"); - Some(next_date.timestamp().as_millisecond() as usize) + if key.year() < 0 { + return Err(Error::new("log file periods require a four-digit year")); + } + let bounds = key + .checked_add(span) + .and_then(|end| self.bounds(now, tz, key, end)) + .map_err(|err| { + Error::new("failed to determine log rotation period").with_source(err) + })?; + Ok(Some(Period { key, bounds })) + } + + fn bounds( + self, + now: Timestamp, + tz: &TimeZone, + key: DateTime, + next: DateTime, + ) -> Result, jiff::Error> { + let offset = tz.to_offset(now); + let mut start = offset.to_timestamp(key)?; + let mut end = offset.to_timestamp(next)?; + + // A repeated hour or minute has two occurrences. A day spans offset changes + // as long as the clock stays on the same date on both sides of the transition. + let tick = SignedDuration::from_nanos(1); + for transition in tz.preceding(now.checked_add(tick)?) { + let at = transition.timestamp(); + if at < start { + break; + } + let before = at.checked_sub(tick)?; + if self != Self::Daily || tz.to_datetime(before).date() != key.date() { + start = at; + break; + } + start = tz.to_offset(before).to_timestamp(key)?; + } + for transition in tz.following(now) { + let at = transition.timestamp(); + if at > end { + break; + } + let after = transition.offset(); + if self != Self::Daily || after.to_datetime(at).date() != key.date() { + end = at; + break; + } + end = after.to_timestamp(next)?; + } + Ok(start..end) } - /// Get the date format string for the rotation policy. - pub fn date_format(&self) -> &'static str { - match *self { - Rotation::Minutely => "%F-%H-%M", - Rotation::Hourly => "%F-%H", - Rotation::Daily => "%F", - Rotation::Never => "%F", + pub(crate) fn date_format(self) -> &'static str { + match self { + Self::Minutely => "%F-%H-%M", + Self::Hourly => "%F-%H", + Self::Daily | Self::Never => "%F", } } + + pub(crate) fn parse_period(self, text: &str) -> Option { + let len = match self { + Self::Never => return None, + Self::Daily => 10, + Self::Hourly => 13, + Self::Minutely => 16, + }; + if text.len() != len + || !text.bytes().enumerate().all(|(i, b)| match i { + 4 | 7 | 10 | 13 => b == b'-', + _ => b.is_ascii_digit(), + }) + { + return None; + } + DateTime::strptime(self.date_format(), text).ok() + } } #[cfg(test)] mod tests { - use std::str::FromStr; - - use jiff::Timestamp; - use jiff::ZonedDateTime; - - use super::Rotation; + use super::*; #[test] - fn test_next_date_timestamp() { - let current_date = ZonedDateTime::from_str("2024-08-10T17:12:52+08[+08]").unwrap(); - - assert_eq!(Rotation::Never.next_date_timestamp(¤t_date), None); - - let expected_date = "2024-08-10T17:13:00+08".parse::().unwrap(); - assert_eq!( - Rotation::Minutely.next_date_timestamp(¤t_date), - Some(expected_date.as_millisecond() as usize) - ); + fn a_calendar_day_spans_the_offset_change() { + let tz = TimeZone::get("America/New_York").unwrap(); + for (before, after, start, end) in [ + ( + "2026-03-08T01:59:59-05", + "2026-03-08T03:00:00-04", + "2026-03-08T00:00:00-05", + "2026-03-09T00:00:00-04", + ), + ( + "2026-11-01T01:59:59-04", + "2026-11-01T01:00:00-05", + "2026-11-01T00:00:00-04", + "2026-11-02T00:00:00-05", + ), + ] { + let expected = start.parse().unwrap()..end.parse().unwrap(); + for now in [before, after] { + let period = Rotation::Daily + .period_at(now.parse().unwrap(), &tz) + .unwrap() + .unwrap(); + assert_eq!(period.bounds, expected); + } + } + } - let expected_date = "2024-08-10T18:00:00+08".parse::().unwrap(); + #[test] + fn repeated_hour_can_start_at_half_past() { + let tz = TimeZone::get("Australia/Lord_Howe").unwrap(); + let now = "2026-04-05T01:45:00+10:30".parse().unwrap(); + let period = Rotation::Hourly.period_at(now, &tz).unwrap().unwrap(); assert_eq!( - Rotation::Hourly.next_date_timestamp(¤t_date), - Some(expected_date.as_millisecond() as usize) + period.bounds, + "2026-04-05T01:30:00+10:30".parse().unwrap() + .."2026-04-05T02:00:00+10:30".parse().unwrap() ); - - let expected_date = "2024-08-11T00:00:00+08".parse::().unwrap(); assert_eq!( - Rotation::Daily.next_date_timestamp(¤t_date), - Some(expected_date.as_millisecond() as usize) + period.key, + "2026-04-05T01:00:00".parse::().unwrap() ); } } diff --git a/appenders/file/tests/global_file_limit.rs b/appenders/file/tests/global_file_limit.rs index dbafda7..5e1724a 100644 --- a/appenders/file/tests/global_file_limit.rs +++ b/appenders/file/tests/global_file_limit.rs @@ -13,178 +13,61 @@ // limitations under the License. use std::fs; +use std::num::NonZeroU64; use std::num::NonZeroUsize; -use std::path::Path; -use std::thread; -use std::time::Duration; +use jiff::tz::TimeZone; use logforth_append_file::FileBuilder; use logforth_core::Append; use logforth_core::record::Record; -use tempfile::TempDir; +use tempfile::tempdir; #[test] -fn test_global_file_count_limit() { - // Create a temporary directory for our test - let temp_dir = TempDir::new().expect("failed to create a temporary directory"); - let max_files = 10; // Small number for testing - let max_size = 100; // Small size to force rotation - - // Create our writer with hourly rotation - let writer = FileBuilder::new(temp_dir.path(), "test_prefix") - .rollover_hourly() - .rollover_size(NonZeroUsize::new(max_size).unwrap()) - .max_log_files(NonZeroUsize::new(max_files).unwrap()) +fn size_limit_retains_the_newest_segments_in_numeric_order() { + let dir = tempdir().unwrap(); + let appender = FileBuilder::new(dir.path(), "test") + .filename_suffix("log") + .rollover_size(NonZeroU64::MIN) + .max_log_files(NonZeroUsize::new(3).unwrap()) .build() .unwrap(); - println!("Starting test_global_file_count_limit"); - - // Write enough data to create multiple files - for i in 0..50 { - writer + for i in 1..=12 { + appender .append( - &Record::builder() - .payload(format_args!("Log entry {}: {}\n", i, "A".repeat(50))) - .build(), + &Record::builder().payload(format_args!("entry {i}")).build(), &[], ) .unwrap(); - writer.flush().unwrap(); } + appender.flush().unwrap(); - // Count the total number of files with our prefix - let files = fs::read_dir(temp_dir.path()) - .unwrap() - .filter_map(|entry| { - let entry = entry.ok()?; - let filename = entry.file_name().to_str()?.to_string(); - if filename.starts_with("test_prefix") { - Some(filename) - } else { - None - } - }) - .collect::>(); - - println!("Found {} files: {:?}", files.len(), files); - - // Assert that the total number of files is limited to max_files - assert!( - files.len() <= max_files, - "Expected at most {} files, but found {}: {:?}", - max_files, - files.len(), - files - ); - - println!("Test passed! File count is limited to {}", max_files); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 3); + for i in 10..=12 { + let record = fs::read_to_string(dir.path().join(format!("test.{i}.log"))).unwrap(); + assert!(record.ends_with(&format!("entry {i}\n"))); + } } -// This test case simulates the issue described: many log files exist across multiple dates, -// but the total count is not properly limited #[test] -fn test_file_limit_across_multiple_dates() { - // Create a temporary directory - let temp_dir = TempDir::new().expect("failed to create a temporary directory"); - let max_files = 10; // Set maximum file count to 10 - let max_size = 50; // Small file size to trigger rotation quickly - - // Create multiple log writers, each with a different filename pattern (simulating different - // dates) - println!("Creating multiple log files with different date patterns"); - - // First batch - simulate March 18 - create_logs( - temp_dir.path(), - max_files, - max_size, - "databend-query-default", - 15, - ); - - // Second batch - simulate March 19 - create_logs( - temp_dir.path(), - max_files, - max_size, - "databend-query-default", - 20, - ); - - // Third batch - simulate March 20 - create_logs( - temp_dir.path(), - max_files, - max_size, - "databend-query-default", - 10, - ); - - // Count all log files - let files = count_log_files(temp_dir.path(), "databend-query-default"); - - println!("Total files across all dates: {}", files.len()); - println!("Files: {:?}", files); - - // Verify if the total number of files exceeds the limit - // Note: If this assertion fails, it means we've reproduced the issue - file count is not - // properly limited - assert!( - files.len() <= max_files, - "Expected at most {} files, but found {} files across multiple dates", - max_files, - files.len() - ); -} +fn startup_applies_one_limit_across_periods() { + let dir = tempdir().unwrap(); + for name in [ + "test.2000-01-01.10", + "test.2000-01-02.2", + "test.2000-01-02.10", + ] { + fs::write(dir.path().join(name), name).unwrap(); + } -// Create a specified number of log files -fn create_logs(dir: &Path, max_files: usize, max_size: usize, filename: &str, count: usize) { - // Create a new log writer for each "date" - let writer = FileBuilder::new(dir, filename) - .rollover_hourly() // Use hourly rotation - .rollover_size(NonZeroUsize::new(max_size).unwrap()) - .max_log_files(NonZeroUsize::new(max_files).unwrap()) + let _appender = FileBuilder::new(dir.path(), "test") + .rollover_daily() + .timezone(TimeZone::UTC) + .rollover_size(NonZeroU64::MIN) + .max_log_files(NonZeroUsize::new(2).unwrap()) .build() .unwrap(); - println!("Creating logs with filename: {filename}"); - - // Write enough data to create the specified number of files - for i in 0..count * 5 { - // Each file needs about 5 writes to rotate - writer - .append( - &Record::builder() - .payload(format_args!( - "Prefix {}, Log {}: {}\n", - filename, - i, - "X".repeat(20) - )) - .build(), - &[], - ) - .unwrap(); - writer.flush().unwrap(); - - // Brief pause to ensure the file system has time to process - thread::sleep(Duration::from_millis(10)); - } -} - -// Count log files with the specified prefix -fn count_log_files(dir: &Path, prefix: &str) -> Vec { - fs::read_dir(dir) - .unwrap() - .filter_map(|entry| { - let entry = entry.ok()?; - let filename = entry.file_name().to_str()?.to_string(); - if filename.starts_with(prefix) { - Some(filename) - } else { - None - } - }) - .collect::>() + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); + assert!(dir.path().join("test.2000-01-02.10").is_file()); } diff --git a/logforth/tests/recursive_logging.rs b/logforth/tests/recursive_logging.rs index 946feec..02dd459 100644 --- a/logforth/tests/recursive_logging.rs +++ b/logforth/tests/recursive_logging.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::num::NonZeroU64; use std::num::NonZeroUsize; use logforth::Diagnostic; @@ -38,7 +39,7 @@ fn test_meta_logging_in_format_works() { let rolling = FileBuilder::new("logs", "example") .layout(CustomLayout("file")) .rollover_minutely() - .rollover_size(NonZeroUsize::new(1024 * 1024).unwrap()) + .rollover_size(NonZeroU64::new(1024 * 1024).unwrap()) .filename_suffix("log") .max_log_files(NonZeroUsize::new(10).unwrap()) .build() From 6a4f374e805dc62f26bdbb55984af669ac848db8 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 18:55:36 +0800 Subject: [PATCH 2/4] docs: split historical changelog and align unreleased entries Move historical release notes (`<= 0.30.1`) into `CHANGELOG-OLD.md` and organize `CHANGELOG.md` under `## Unreleased` using uniform, caller-facing `Breaking changes`, `New features`, `Improvements`, and `Bug fixes` entries covering all user-visible changes since `0.30.1`. Signed-off-by: tison --- CHANGELOG-OLD.md | 480 +++++++++++++++++++++++++++++++++++++++++++++ CHANGELOG.md | 499 ++--------------------------------------------- 2 files changed, 500 insertions(+), 479 deletions(-) create mode 100644 CHANGELOG-OLD.md diff --git a/CHANGELOG-OLD.md b/CHANGELOG-OLD.md new file mode 100644 index 0000000..e09ce20 --- /dev/null +++ b/CHANGELOG-OLD.md @@ -0,0 +1,480 @@ +# Historical Changelog + +## [0.30.1] 2026-06-03 + +### Improvements + +* Leverage `log::kv::Key::to_static_str` when possible. + +## [0.30.0] 2026-06-03 + +### Breaking changes + +* Bump minimum supported Rust version (MSRV) to 1.89.0. +* `Append` has no more `exit` method. Users should keep a logger handle and compose `Logger::flush()` with their own graceful shutdown logic. +* `Async` appender's `flush` method is now blocking until all buffered logs are flushed by worker threads. Any errors during flushing will be propagated back to the `flush` caller. +* `Record::payload` is now `std::fmt::Arguments` instead of `Cow<'static, str>`. +* `RecordOwned::as_record` has been removed; use `RecordOwned::with` instead. (This is a limitation of Rust as described [here](https://github.com/rust-lang/rust/issues/92698#issuecomment-3311144848).) +* `logforth_core::Error::with_source` now set the optional source field instead of append a sources list. +* `logforth_core::kv` has been totally redesigned to decouple from `value-bag`. See [PR-229](https://github.com/fast/logforth/pull/229) for details. +* `logforth_core::filter::env_filter` is now factored out into `logforth-filter-rustlog` crate. `EnvFilter` is renamed to `RustLogFilter`. So do other related types and feature flags. + +## [0.29.1] 2025-11-03 + +### Bug fixes + +* `Record::target_static` should return `&'static str` instead of `&str`. + +## [0.29.0] 2025-11-03 + +### Breaking changes + +* Rename `DefaultTrap` to `BestEffortTrap` for better clarity. +* Rename `logforth_core::record::Metadata` to `FilterCriteria`. +* Redesign `LevelFilter` to allow different comparison methods. +* Redesign `Level` as opentelemetry severity numbers. + * Add `Level::Fatal` variant to represent fatal level logs. +* `LogStarterStdStreamBuilder`'s setter follows builder pattern. + * `LogStarterStdStreamBuilder::with_layout` is now `layout`. + * `LogStarterStdStreamBuilder::with_filter` is now `filter`. + +### New features + +* Add `logforth-diagnostic-task-local` and `TaskLocalDiagnostic` to support task-local key-value context. + +### Bug fixes + +* Fix `FastraceDiagnostic` does not format `trace_id` and `span_id` as hex strings. + +## [0.28.1] 2025-10-06 + +### Documentation changes + +* `doc_auto_cfg` is now `doc_cfg`. + +## [0.28.0] 2025-10-06 + +### Breaking changes + +#### Interfaces + +* To work with the `log` crate, now it's recommended to add the "starter-log" feature flag and set both: + ```rust + fn main() { + logforth::starter_log::builder().apply(); + } + ``` +* `TextLayout` is now behind `layout-text` feature flag, and colored is always available when the feature is enabled. +* `EnvFilter` is now self-hosted. Some methods may be changed, but the general user experience should retain: + * `EnvFilter`'s constructors (`from_env`, etc.) are moved to `EnvFilterBuilder`. +* There is no longer `NonBlocking` related logics. + +#### File appender + +* `SingleFile` appender is removed. You can replace it with `append::File`. +* `RollingFile` is now `File` and is behind `append-file` flag. +* `File` appender now requires `filename` when constructing. +* `File`'s `filename_prefix` is now renamed to mandatory `filename`. +* `File`'s `max_log_files` now takes `NonZeroUsize`. +* `File`'s rollover strategy methods has been changed: + * `max_file_size` -> `rollover_size` and takes `NonZeroUsize` + * `rotation` -> `rollover_minutely`, `rollover_hourly`, `rollover_daily` + * By default, no rollover is performed. +* Rollover filename strategy has been changed: + ``` + given: + filename = app + filename_suffix = log + max_log_files = 3 + + before rollover: + app.log + app.1.log + app.2.log + + after rollover: + app.log + app.1.log - old app.log + app.2.log - old app.1.log + - old app.2.log deleted + ``` + +#### Developments + +* All interfaces that return `anyhow::Result` is now using a result over `logforth::Error`. +* Internal log structs are migrated from `log` crate to self-hosted types. This should not affect most users, but if you are customizing appender, layout, filter, and diagnostic, you should replace `log::Record`, `log::Metadata`, or `log::Level`, with `logforth::Record`, `logforth::Metadata`, or `logforth::Level`. +* All components are factored out into their own crates. + +#### Minors + +* `JsonLayout` now collects diagnostics context into a separate field `diags`. +* Upgrade to opentelemetry 0.31.0. + +### Notable changes + +* Timestamp format in `TextLayout`, `JsonLayout`, and `LogfmtLayout` is changed from RFC 9557 to RFC 3339 format. + * That is, from "2025-01-10T15:22:37.868815+08:00[Asia/Shanghai]" to "2025-01-10T15:22:37.868815+08:00". + +### New features + +* `PlainTextLayout` is added to support plain text format without any extra dependency. +* `Async` appender is added to support async logging with configurable buffer size and worker threads. +* `Trap` trait and a default `DefaultTrap` is added to support handling internal errors. + +## [0.27.0] 2025-08-18 + +### Notable changes + +* Bump the Rust edition to 2024. +* Claim stabilize targets for the crate. + +## [0.26.2] 2025-07-13 + +### Bug fixes + +* `RollingFile` appender now correctly delete old files on systems where `create_time` is not available ([#142](https://github.com/fast/logforth/pull/142)) + +## [0.26.1] 2025-06-05 + +### New features + +* Implement `Testing` appender that sends logs to `eprintln!`. + +## [0.26.0] 2025-06-04 + +### Breaking changes + +* `OpenTelemetryLogBuild::build` is now infallible. +* Upgrade to opentelemetry 0.30.0. +* Feature flags are renamed with prefix like `append-rolling-file` and `layout-json`. +* `OpenTelemetryLog` appender now accepts `MakeBody` over `Layout`. +* `Filter::matches` and `Filter::enabled` now take an extra `&[Box]` argument to retrieve the mapped diagnostics context. + +## [0.25.0] 2025-05-15 + +### Breaking changes + +* `OpenTelemetryLogBuild::new` now accepts `opentelemetry_otlp::LogExporter`. +* Bump minimum supported Rust version (MSRV) to 1.85.0. + +### Improvements + +* `FastraceDiagnostic` now exports `sampled` attribute. + +## [0.24.0] 2025-04-09 + +### Breaking changes + +* `Diagnostic` is now a trait. `Visitor`'s method signature is simplified. +* `Append::flush` is now fallible. +* `Diagnostic`'s and `Visitor`'s `visit` methods are fallible. +* `NonBlocking` related types and the feature flag are now private. +* `logforth::Builder` is renamed to `logforth::LoggerBuilder`. +* `LoggerBuilder` has no longer an option to configure the global `max_level`. Check its documentation for more details. +* Constructing `RollingFile` and `Syslog` appender is heavily simplified. + +Before: + +```rust +fn construct_rolling_file() { + let rolling_writer = RollingFileWriter::builder() + .rotation(Rotation::Daily) + .filename_prefix("app_log") + .build("logs") + .unwrap(); + + let (non_blocking, _guard) = rolling_file::non_blocking(rolling_writer).finish(); + + logforth::builder() + .dispatch(|d| { + d.filter(log::LevelFilter::Trace) + .append(RollingFile::new(non_blocking).with_layout(JsonLayout::default())) + }) + .apply(); +} + +fn construct_syslog() { + let syslog_writer = SyslogWriter::tcp_well_known().unwrap(); + let (non_blocking, _guard) = syslog::non_blocking(syslog_writer).finish(); + + logforth::builder() + .dispatch(|d| { + d.filter(log::LevelFilter::Trace) + .append(Syslog::new(non_blocking)) + }) + .apply(); +} +``` + +After: + +```rust +fn construct_rolling_file() { + let (rolling_writer, _guard) = RollingFileBuilder::new("logs") + .layout(JsonLayout::default()) + .rotation(Rotation::Daily) + .filename_prefix("app_log") + .build() + .unwrap(); + + logforth::builder() + .dispatch(|d| d.filter(log::LevelFilter::Trace).append(rolling_writer)) + .apply(); +} + +fn construct_syslog() { + let (append, _guard) = SyslogBuilder::tcp_well_known().unwrap().build(); + + logforth::builder() + .dispatch(|d| d.filter(log::LevelFilter::Trace).append(append)) + .apply(); +} +``` + + +### New features + +* Add `LogfmtLayout` to support logfmt format. +* Add `GoogleStructuredLogLayout` to support Google structured log format. +* `LoggerBuilder` now has a `build` method to construct the `Logger` for use. + +## [0.23.1] 2025-03-23 + +### Improvements + +* Upgrade to opentelemetry 0.29.0 to avoid transitive dependency to axum. + +## [0.23.0] 2025-03-17 + +### Breaking changes + +* `Layout` and `Filter` as traits +* Default features are now empty; no more `colored` in default. + +### New features + +* Add `StaticDiagnostic` for globally configuring context. + +## [0.22.1] 2025-02-20 + +### Refactor + +* Revisit all `pub(crate)` methods: + * Expose `Layout::format` and all layout impls `format` method. + * Expose `Nonblocking` methods to make it usable outside this crate. + +## [0.22.0] 2025-02-13 + +### Breaking changes + +* Upgrade `jiff` to 0.2.0 and `opentelemetry` to 0.28.0. + +## [0.21.0] 2025-01-15 + +### Breaking changes + +* Re-export `colored` to decouple the dependency. In addition, replace the `no-color` feature flag with the `colored` feature flag. + +## [0.20.0] 2025-01-08 + +### Breaking changes + +* Bump MSRV to 1.80 for upgrading `colored` to 3.0. +* Layout and Appender now accept a new argument `diagnostics: &[Diagnostic]` to retrieve the mapped diagnostics context. Users can use `logforth::diagnostic::Visitor` to visit the diagnostics context. + +### New features + +* Add `logforth::diagnostic::FastraceDiagnostic` to support attaching trace id to as key-value context. +* Add `logforth::diagnostic::ThreadLocalDiagnostic` to support attaching thread local key-value context. + +## [0.19.2] 2025-01-03 + +### Fixes + +* Fix minimum version required for env_filter should be 0.1.1 ([#87](https://github.com/fast/logforth/pull/87)). + +## [0.19.1] 2024-12-20 + +### Refactor + +* Migrate from `log`'s `kv_unstable` feature to `kv` feature ([#85](https://github.com/fast/logforth/pull/85)). + +## [0.19.0] 2024-12-07 + +### Breaking Changes + +* `module_path` is replaced by `target` in `JsonLayout` and `TextLayout` ([#82](https://github.com/fast/logforth/pull/82)). +* Error perform logging now prints error in Debug format ([#84](https://github.com/fast/logforth/pull/84)) + +## [0.18.1] 2024-11-17 + +### New features + +* Re-export `broadcast` and `native_tls` constructors from fasyslog ([#81](https://github.com/fast/logforth/pull/81)). + +## [0.18.0] 2024-11-14 + +### Breaking changes + +* The mapping between syslog severity and log's level is changed. + * `log::Level::Error` is mapped to `syslog::Severity::Error` (unchanged). + * `log::Level::Warn` is mapped to `syslog::Severity::Warning` (unchanged). + * `log::Level::Info` is mapped to `syslog::Severity::Notice` (changed). + * `log::Level::Debug` is mapped to `syslog::Severity::Info` (changed). + * `log::Level::Trace` is mapped to `syslog::Severity::Debug` (unchanged). + +### New features + +* Add `journald` feature to support journald appenders ([#80](https://github.com/fast/logforth/pull/80)). + +## [0.17.1] 2024-11-12 + +### Refactors + +* Change the re-export of `syslog` to `logforth::syslog::fasyslog` ([#74](https://github.com/fast/logforth/pull/74)) + +## [0.17.0] 2024-11-12 + +### New features + +* Add `syslog` feature to support syslog appenders ([#72](https://github.com/fast/logforth/pull/72)) + +### Breaking changes + +Two breaking changes in [#72](https://github.com/fast/logforth/pull/72): + +1. `rolling_file` feature flag is renamed to `rolling-file`. +2. `NonBlocking` related structures and methods are relocated, now you'd construct a non-blocking like: + +```rust +fn main() { + let rolling_writer = RollingFileWriter::builder() + .rotation(Rotation::Daily) + .filename_prefix("app_log") + .build("logs") + .unwrap(); + + let (non_blocking, _guard) = rolling_file::non_blocking(rolling_writer).finish(); + + logforth::builder() + .dispatch(|d| { + d.filter(log::LevelFilter::Trace) + .append(RollingFile::new(non_blocking).with_layout(JsonLayout::default())) + }) + .apply(); +} +``` + +or: + +```rust +fn main() { + let syslog_writer = SyslogWriter::tcp_well_known().unwrap(); + let (non_blocking, _guard) = syslog::non_blocking(syslog_writer).finish(); + + logforth::builder() + .dispatch(|d| { + d.filter(log::LevelFilter::Trace) + .append(Syslog::new(non_blocking)) + }) + .apply(); +} +``` + +Note that each `NonBlocking` now has a type parameter to ensure that they match the corresponding appenders. + +## [0.16.0] 2024-10-30 + +### Breaking changes + +Two minor breaking changes in [#71](https://github.com/fast/logforth/pull/71): + +1. `JsonLayout`'s field `tz` is now private. You can change it with the new `timezone` method, like `JsonLayout::default().timezone(TimeZone::UTC)`. +2. `DispatchBuilder` now always accepts `filter` first, and then `append`. Once an `append` is configured, no more `filter` can be added. This is for a strict order on config so that the code is more consistent. + +## [0.15.0] 2024-10-30 + +### Breaking changes + +API is further improve in both [#69](https://github.com/fast/logforth/pull/69) and [#70](https://github.com/fast/logforth/pull/70). + +Now the logger build logic is like: + +```rust +use log::LevelFilter; +use logforth::append; +use logforth::layout::JsonLayout; + +fn main() { + logforth::builder() + .dispatch(|b| b.filter(LevelFilter::Debug).append(append::Stderr::default().with_layout(JsonLayout::default()))) + .dispatch(|b| b.filter(LevelFilter::Info).append(append::Stdout::default().with_layout(JsonLayout::default()))) + .apply(); +} +``` + +And we provide a convenient way to build the logger with default setup (stderr or stdout, with RUST_LOG envvar respected): + +```rust +fn main() { + logforth::stderr().apply(); + // or logforth::stdout().apply(); // for logging to stdout +} +``` + +## [0.14.0] 2024-10-28 + +### Breaking changes + +1. refactor: layouts and encoders should be nested to appenders ([#64](https://github.com/fast/logforth/pull/64)) + + Previous code: + + ```rust + fn main() { + Logger::new() + .dispatch( + Dispatch::new() + .filter(LevelFilter::Trace) + .layout(JsonLayout::default()) + .append(append::Stdout), + ) + .apply() + .unwrap(); + + log::error!("Hello error!"); + log::warn!("Hello warn!"); + log::info!("Hello info!"); + log::debug!("Hello debug!"); + log::trace!("Hello trace!"); + } + ``` + + New code: + + ```rust + fn main() { + Logger::new() + .dispatch( + Dispatch::new() + .filter(LevelFilter::Trace) + .append(append::Stdout::default().with_layout(JsonLayout::default())), + ) + .apply() + .unwrap(); + + log::error!("Hello error!"); + log::warn!("Hello warn!"); + log::info!("Hello info!"); + log::debug!("Hello debug!"); + log::trace!("Hello trace!"); + } + ``` + + Besides, the default layout of Stdout, Stderr, and RollingFile is changed from `IdenticalLayout` to `TextLayout`. + +2. refactor: unify level/target filter to directive filter ([#65](https://github.com/fast/logforth/pull/65)) + + Most `From` conversions are kept so that typically you won't notice the change. But if you directly use `LevelFilter` and `TargetFilter`, they are now removed. The functionalities can be covered by `EnvFilter`. + + Also, the feature flag `env-filter` is removed. The `EnvFilter` is always available now. diff --git a/CHANGELOG.md b/CHANGELOG.md index ca72f38..4708359 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,493 +1,34 @@ -# CHANGELOG +# Changelog -All notable changes to this project will be documented in this file. +All significant changes to this project will be documented in this file. ## Unreleased ### Breaking changes -* Bump minimum supported Rust version (MSRV) to 1.91.0. -* `logforth-append-opentelemetry` upgrades `opentelemetry`, `opentelemetry-otlp` and `opentelemetry_sdk` to 0.33.1. -* Upgrade `jiff` to 1.0. -* Redesign `logforth_core::Error` without `anyhow`, boxing its payload and removing `with_context`, `sources`, `from_io_error`, and `from_fmt_error`. -* Replace `Trap` and `BestEffortTrap` with `ErrorSink` (`StderrErrorSink` and `BlackHoleErrorSink` under `error`), add `LoggerBuilder::error_sink` and `DispatchBuilder::error_sink` overrides, and remove `FileBuilder::trap`. -* Redesign `logforth-append-file` to write directly to period- and ascending-sequence-named segments (`1, 2, ...` from oldest to newest, replacing reverse-shifted archives and the unnumbered active file when rotating), add `FileBuilder::timezone`, take `NonZeroU64` in `rollover_size`, and count the active segment toward `max_log_files`. - -## [0.30.1] 2026-06-03 - -### Improvements - -* Leverage `log::kv::Key::to_static_str` when possible. - -## [0.30.0] 2026-06-03 - -### Breaking changes - -* Bump minimum supported Rust version (MSRV) to 1.89.0. -* `Append` has no more `exit` method. Users should keep a logger handle and compose `Logger::flush()` with their own graceful shutdown logic. -* `Async` appender's `flush` method is now blocking until all buffered logs are flushed by worker threads. Any errors during flushing will be propagated back to the `flush` caller. -* `Record::payload` is now `std::fmt::Arguments` instead of `Cow<'static, str>`. -* `RecordOwned::as_record` has been removed; use `RecordOwned::with` instead. (This is a limitation of Rust as described [here](https://github.com/rust-lang/rust/issues/92698#issuecomment-3311144848).) -* `logforth_core::Error::with_source` now set the optional source field instead of append a sources list. -* `logforth_core::kv` has been totally redesigned to decouple from `value-bag`. See [PR-229](https://github.com/fast/logforth/pull/229) for details. -* `logforth_core::filter::env_filter` is now factored out into `logforth-filter-rustlog` crate. `EnvFilter` is renamed to `RustLogFilter`. So do other related types and feature flags. - -## [0.29.1] 2025-11-03 - -### Bug fixes - -* `Record::target_static` should return `&'static str` instead of `&str`. - -## [0.29.0] 2025-11-03 - -### Breaking changes - -* Rename `DefaultTrap` to `BestEffortTrap` for better clarity. -* Rename `logforth_core::record::Metadata` to `FilterCriteria`. -* Redesign `LevelFilter` to allow different comparison methods. -* Redesign `Level` as opentelemetry severity numbers. - * Add `Level::Fatal` variant to represent fatal level logs. -* `LogStarterStdStreamBuilder`'s setter follows builder pattern. - * `LogStarterStdStreamBuilder::with_layout` is now `layout`. - * `LogStarterStdStreamBuilder::with_filter` is now `filter`. - -### New features - -* Add `logforth-diagnostic-task-local` and `TaskLocalDiagnostic` to support task-local key-value context. - -### Bug fixes - -* Fix `FastraceDiagnostic` does not format `trace_id` and `span_id` as hex strings. - -## [0.28.1] 2025-10-06 - -### Documentation changes - -* `doc_auto_cfg` is now `doc_cfg`. - -## [0.28.0] 2025-10-06 - -### Breaking changes - -#### Interfaces - -* To work with the `log` crate, now it's recommended to add the "starter-log" feature flag and set both: - ```rust - fn main() { - logforth::starter_log::builder().apply(); - } - ``` -* `TextLayout` is now behind `layout-text` feature flag, and colored is always available when the feature is enabled. -* `EnvFilter` is now self-hosted. Some methods may be changed, but the general user experience should retain: - * `EnvFilter`'s constructors (`from_env`, etc.) are moved to `EnvFilterBuilder`. -* There is no longer `NonBlocking` related logics. - -#### File appender - -* `SingleFile` appender is removed. You can replace it with `append::File`. -* `RollingFile` is now `File` and is behind `append-file` flag. -* `File` appender now requires `filename` when constructing. -* `File`'s `filename_prefix` is now renamed to mandatory `filename`. -* `File`'s `max_log_files` now takes `NonZeroUsize`. -* `File`'s rollover strategy methods has been changed: - * `max_file_size` -> `rollover_size` and takes `NonZeroUsize` - * `rotation` -> `rollover_minutely`, `rollover_hourly`, `rollover_daily` - * By default, no rollover is performed. -* Rollover filename strategy has been changed: - ``` - given: - filename = app - filename_suffix = log - max_log_files = 3 - - before rollover: - app.log - app.1.log - app.2.log - - after rollover: - app.log - app.1.log - old app.log - app.2.log - old app.1.log - - old app.2.log deleted - ``` - -#### Developments - -* All interfaces that return `anyhow::Result` is now using a result over `logforth::Error`. -* Internal log structs are migrated from `log` crate to self-hosted types. This should not affect most users, but if you are customizing appender, layout, filter, and diagnostic, you should replace `log::Record`, `log::Metadata`, or `log::Level`, with `logforth::Record`, `logforth::Metadata`, or `logforth::Level`. -* All components are factored out into their own crates. - -#### Minors - -* `JsonLayout` now collects diagnostics context into a separate field `diags`. -* Upgrade to opentelemetry 0.31.0. - -### Notable changes - -* Timestamp format in `TextLayout`, `JsonLayout`, and `LogfmtLayout` is changed from RFC 9557 to RFC 3339 format. - * That is, from "2025-01-10T15:22:37.868815+08:00[Asia/Shanghai]" to "2025-01-10T15:22:37.868815+08:00". - -### New features - -* `PlainTextLayout` is added to support plain text format without any extra dependency. -* `Async` appender is added to support async logging with configurable buffer size and worker threads. -* `Trap` trait and a default `DefaultTrap` is added to support handling internal errors. - -## [0.27.0] 2025-08-18 - -### Notable changes - -* Bump the Rust edition to 2024. -* Claim stabilize targets for the crate. - -## [0.26.2] 2025-07-13 - -### Bug fixes - -* `RollingFile` appender now correctly delete old files on systems where `create_time` is not available ([#142](https://github.com/fast/logforth/pull/142)) - -## [0.26.1] 2025-06-05 +* Raise the minimum supported Rust version (MSRV) from 1.89.0 to 1.91.0. +* Upgrade `jiff` from 0.2 to 1.0 in `logforth-append-file`, `logforth-layout-json`, `logforth-layout-logfmt`, and `logforth-layout-text`. +* Upgrade `opentelemetry`, `opentelemetry-otlp`, and `opentelemetry_sdk` from 0.31.0 to 0.33.1 in `logforth-append-opentelemetry`. +* Remove the `anyhow` dependency from `logforth-core` and redesign `Error`: `Error::new` now accepts `impl Into>`, `Error::with_source` accepts `impl Into>` instead of `impl Into` and replaces any existing source instead of panicking, and `Error::{with_context, sources, from_io_error, from_fmt_error}` are removed. Walk `.source()` for causal chains and construct descriptive `Error::new(...).with_source(...)` values at call sites. +* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`. Configure runtime error handling via `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log` builders instead. +* `FutureExt::with_task_local_context` in `logforth-diagnostic-task-local` now accepts `IntoIterator` where `K: Into` and `V: Into` instead of `IntoIterator`, preserving typed values instead of converting them to strings; pass keys and values directly without `.into()` where type inference would otherwise be ambiguous. +* `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover. Unrotated output remains `[.]`, time-only rotation writes `.[.]`, and size rotation numbers segments in ascending order from `1` (oldest) as `[.].[.]`; `max_log_files` counts the active file toward the retention limit, and files created under the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed. +* `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after; update callers passing `NonZeroUsize` to pass `NonZeroU64`. +* `FileBuilder::build` in `logforth-append-file` now returns `Err` when `filename` or `filename_suffix` is empty, `.` or `..`, or contains path separators or NUL bytes. ### New features -* Implement `Testing` appender that sends logs to `eprintln!`. - -## [0.26.0] 2025-06-04 - -### Breaking changes - -* `OpenTelemetryLogBuild::build` is now infallible. -* Upgrade to opentelemetry 0.30.0. -* Feature flags are renamed with prefix like `append-rolling-file` and `layout-json`. -* `OpenTelemetryLog` appender now accepts `MakeBody` over `Layout`. -* `Filter::matches` and `Filter::enabled` now take an extra `&[Box]` argument to retrieve the mapped diagnostics context. - -## [0.25.0] 2025-05-15 - -### Breaking changes - -* `OpenTelemetryLogBuild::new` now accepts `opentelemetry_otlp::LogExporter`. -* Bump minimum supported Rust version (MSRV) to 1.85.0. +* Add `Error::message` in `logforth-core` to borrow the error's own message string. +* Add `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, and `starter_log::{LogStarterBuilder, LogStarterTestingBuilder, LogStarterStdStreamBuilder}::error_sink`, and implement `ErrorSink` for `Arc` and `&'static T` where `T: ErrorSink + ?Sized`. +* Add `FileBuilder::timezone` in `logforth-append-file` (and re-export `jiff`) to configure the timezone used for rotation boundaries and segment filenames, defaulting to the system timezone. ### Improvements -* `FastraceDiagnostic` now exports `sampled` attribute. - -## [0.24.0] 2025-04-09 - -### Breaking changes - -* `Diagnostic` is now a trait. `Visitor`'s method signature is simplified. -* `Append::flush` is now fallible. -* `Diagnostic`'s and `Visitor`'s `visit` methods are fallible. -* `NonBlocking` related types and the feature flag are now private. -* `logforth::Builder` is renamed to `logforth::LoggerBuilder`. -* `LoggerBuilder` has no longer an option to configure the global `max_level`. Check its documentation for more details. -* Constructing `RollingFile` and `Syslog` appender is heavily simplified. - -Before: - -```rust -fn construct_rolling_file() { - let rolling_writer = RollingFileWriter::builder() - .rotation(Rotation::Daily) - .filename_prefix("app_log") - .build("logs") - .unwrap(); - - let (non_blocking, _guard) = rolling_file::non_blocking(rolling_writer).finish(); - - logforth::builder() - .dispatch(|d| { - d.filter(log::LevelFilter::Trace) - .append(RollingFile::new(non_blocking).with_layout(JsonLayout::default())) - }) - .apply(); -} - -fn construct_syslog() { - let syslog_writer = SyslogWriter::tcp_well_known().unwrap(); - let (non_blocking, _guard) = syslog::non_blocking(syslog_writer).finish(); - - logforth::builder() - .dispatch(|d| { - d.filter(log::LevelFilter::Trace) - .append(Syslog::new(non_blocking)) - }) - .apply(); -} -``` - -After: - -```rust -fn construct_rolling_file() { - let (rolling_writer, _guard) = RollingFileBuilder::new("logs") - .layout(JsonLayout::default()) - .rotation(Rotation::Daily) - .filename_prefix("app_log") - .build() - .unwrap(); - - logforth::builder() - .dispatch(|d| d.filter(log::LevelFilter::Trace).append(rolling_writer)) - .apply(); -} - -fn construct_syslog() { - let (append, _guard) = SyslogBuilder::tcp_well_known().unwrap().build(); - - logforth::builder() - .dispatch(|d| d.filter(log::LevelFilter::Trace).append(append)) - .apply(); -} -``` - - -### New features - -* Add `LogfmtLayout` to support logfmt format. -* Add `GoogleStructuredLogLayout` to support Google structured log format. -* `LoggerBuilder` now has a `build` method to construct the `Logger` for use. - -## [0.23.1] 2025-03-23 - -### Improvements - -* Upgrade to opentelemetry 0.29.0 to avoid transitive dependency to axum. - -## [0.23.0] 2025-03-17 - -### Breaking changes - -* `Layout` and `Filter` as traits -* Default features are now empty; no more `colored` in default. +* Implement `Copy` for `kv::{Key, KeyView, Value, ValueView}`, `From<&'static str>` and `From` for `kv::KeyOwned`, `From` scalar and string conversions for `kv::ValueOwned`, and `kv::Visitor` for `FnMut(KeyView, ValueView) -> Result<(), Error>` closures in `logforth-core`. +* Make `LevelFilter::test` a `const fn` in `logforth-core`. +* Implement `Clone` for `RustLogFilter` and `Directive` in `logforth-filter-rustlog`. -### New features - -* Add `StaticDiagnostic` for globally configuring context. - -## [0.22.1] 2025-02-20 - -### Refactor - -* Revisit all `pub(crate)` methods: - * Expose `Layout::format` and all layout impls `format` method. - * Expose `Nonblocking` methods to make it usable outside this crate. - -## [0.22.0] 2025-02-13 - -### Breaking changes - -* Upgrade `jiff` to 0.2.0 and `opentelemetry` to 0.28.0. - -## [0.21.0] 2025-01-15 - -### Breaking changes - -* Re-export `colored` to decouple the dependency. In addition, replace the `no-color` feature flag with the `colored` feature flag. - -## [0.20.0] 2025-01-08 - -### Breaking changes - -* Bump MSRV to 1.80 for upgrading `colored` to 3.0. -* Layout and Appender now accept a new argument `diagnostics: &[Diagnostic]` to retrieve the mapped diagnostics context. Users can use `logforth::diagnostic::Visitor` to visit the diagnostics context. - -### New features - -* Add `logforth::diagnostic::FastraceDiagnostic` to support attaching trace id to as key-value context. -* Add `logforth::diagnostic::ThreadLocalDiagnostic` to support attaching thread local key-value context. - -## [0.19.2] 2025-01-03 - -### Fixes - -* Fix minimum version required for env_filter should be 0.1.1 ([#87](https://github.com/fast/logforth/pull/87)). - -## [0.19.1] 2024-12-20 - -### Refactor - -* Migrate from `log`'s `kv_unstable` feature to `kv` feature ([#85](https://github.com/fast/logforth/pull/85)). - -## [0.19.0] 2024-12-07 - -### Breaking Changes - -* `module_path` is replaced by `target` in `JsonLayout` and `TextLayout` ([#82](https://github.com/fast/logforth/pull/82)). -* Error perform logging now prints error in Debug format ([#84](https://github.com/fast/logforth/pull/84)) - -## [0.18.1] 2024-11-17 - -### New features - -* Re-export `broadcast` and `native_tls` constructors from fasyslog ([#81](https://github.com/fast/logforth/pull/81)). - -## [0.18.0] 2024-11-14 - -### Breaking changes - -* The mapping between syslog severity and log's level is changed. - * `log::Level::Error` is mapped to `syslog::Severity::Error` (unchanged). - * `log::Level::Warn` is mapped to `syslog::Severity::Warning` (unchanged). - * `log::Level::Info` is mapped to `syslog::Severity::Notice` (changed). - * `log::Level::Debug` is mapped to `syslog::Severity::Info` (changed). - * `log::Level::Trace` is mapped to `syslog::Severity::Debug` (unchanged). - -### New features - -* Add `journald` feature to support journald appenders ([#80](https://github.com/fast/logforth/pull/80)). - -## [0.17.1] 2024-11-12 - -### Refactors - -* Change the re-export of `syslog` to `logforth::syslog::fasyslog` ([#74](https://github.com/fast/logforth/pull/74)) - -## [0.17.0] 2024-11-12 - -### New features - -* Add `syslog` feature to support syslog appenders ([#72](https://github.com/fast/logforth/pull/72)) - -### Breaking changes - -Two breaking changes in [#72](https://github.com/fast/logforth/pull/72): - -1. `rolling_file` feature flag is renamed to `rolling-file`. -2. `NonBlocking` related structures and methods are relocated, now you'd construct a non-blocking like: - -```rust -fn main() { - let rolling_writer = RollingFileWriter::builder() - .rotation(Rotation::Daily) - .filename_prefix("app_log") - .build("logs") - .unwrap(); - - let (non_blocking, _guard) = rolling_file::non_blocking(rolling_writer).finish(); - - logforth::builder() - .dispatch(|d| { - d.filter(log::LevelFilter::Trace) - .append(RollingFile::new(non_blocking).with_layout(JsonLayout::default())) - }) - .apply(); -} -``` - -or: - -```rust -fn main() { - let syslog_writer = SyslogWriter::tcp_well_known().unwrap(); - let (non_blocking, _guard) = syslog::non_blocking(syslog_writer).finish(); - - logforth::builder() - .dispatch(|d| { - d.filter(log::LevelFilter::Trace) - .append(Syslog::new(non_blocking)) - }) - .apply(); -} -``` - -Note that each `NonBlocking` now has a type parameter to ensure that they match the corresponding appenders. - -## [0.16.0] 2024-10-30 - -### Breaking changes - -Two minor breaking changes in [#71](https://github.com/fast/logforth/pull/71): - -1. `JsonLayout`'s field `tz` is now private. You can change it with the new `timezone` method, like `JsonLayout::default().timezone(TimeZone::UTC)`. -2. `DispatchBuilder` now always accepts `filter` first, and then `append`. Once an `append` is configured, no more `filter` can be added. This is for a strict order on config so that the code is more consistent. - -## [0.15.0] 2024-10-30 - -### Breaking changes - -API is further improve in both [#69](https://github.com/fast/logforth/pull/69) and [#70](https://github.com/fast/logforth/pull/70). - -Now the logger build logic is like: - -```rust -use log::LevelFilter; -use logforth::append; -use logforth::layout::JsonLayout; - -fn main() { - logforth::builder() - .dispatch(|b| b.filter(LevelFilter::Debug).append(append::Stderr::default().with_layout(JsonLayout::default()))) - .dispatch(|b| b.filter(LevelFilter::Info).append(append::Stdout::default().with_layout(JsonLayout::default()))) - .apply(); -} -``` - -And we provide a convenient way to build the logger with default setup (stderr or stdout, with RUST_LOG envvar respected): - -```rust -fn main() { - logforth::stderr().apply(); - // or logforth::stdout().apply(); // for logging to stdout -} -``` - -## [0.14.0] 2024-10-28 - -### Breaking changes - -1. refactor: layouts and encoders should be nested to appenders ([#64](https://github.com/fast/logforth/pull/64)) - - Previous code: - - ```rust - fn main() { - Logger::new() - .dispatch( - Dispatch::new() - .filter(LevelFilter::Trace) - .layout(JsonLayout::default()) - .append(append::Stdout), - ) - .apply() - .unwrap(); - - log::error!("Hello error!"); - log::warn!("Hello warn!"); - log::info!("Hello info!"); - log::debug!("Hello debug!"); - log::trace!("Hello trace!"); - } - ``` - - New code: - - ```rust - fn main() { - Logger::new() - .dispatch( - Dispatch::new() - .filter(LevelFilter::Trace) - .append(append::Stdout::default().with_layout(JsonLayout::default())), - ) - .apply() - .unwrap(); - - log::error!("Hello error!"); - log::warn!("Hello warn!"); - log::info!("Hello info!"); - log::debug!("Hello debug!"); - log::trace!("Hello trace!"); - } - ``` - - Besides, the default layout of Stdout, Stderr, and RollingFile is changed from `IdenticalLayout` to `TextLayout`. - -2. refactor: unify level/target filter to directive filter ([#65](https://github.com/fast/logforth/pull/65)) - - Most `From` conversions are kept so that typically you won't notice the change. But if you directly use `LevelFilter` and `TargetFilter`, they are now removed. The functionalities can be covered by `EnvFilter`. +### Bug fixes - Also, the feature flag `env-filter` is removed. The `EnvFilter` is always available now. +* `Logger::log` and `Logger::flush` in `logforth-core` no longer panic when writing internal error reports to standard error fails. +* `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, avoids panicking on matching prefix and suffix edge cases or out-of-range timestamps, and avoids truncating rotation timestamps or file sizes on 32-bit targets. From 2102c0690c5f4b26f308d967fdfdbf2f56c5e002 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 19:42:28 +0800 Subject: [PATCH 3/4] docs(append-file): align File and FileBuilder documentation conventions Standardize crate, type, and method documentation across `logforth-append-file` with consistent noun-phrase type summaries, present-tense method contracts, explicit default annotations, structured `# Errors` conditions on `FileBuilder::build`, and unified crate-level segment naming and retention sections. Signed-off-by: tison --- appenders/file/README.md | 17 +++--- appenders/file/src/append.rs | 109 ++++++++++++++++++----------------- appenders/file/src/lib.rs | 70 +++++++++++++--------- 3 files changed, 107 insertions(+), 89 deletions(-) diff --git a/appenders/file/README.md b/appenders/file/README.md index a41c8f9..cce2776 100644 --- a/appenders/file/README.md +++ b/appenders/file/README.md @@ -1,14 +1,13 @@ # File Appender -This appender is originally a fork of [tracing-appender](https://crates.io/crates/tracing-appender). +File appender for Logforth supporting single-file output and direct-write time- and size-based segment rotation. -Later, we rewrite it completely to support: +* Writes directly to append-mode segment files without renaming active files on rollover. +* Supports time-based (`Minutely`, `Hourly`, `Daily` with configurable `TimeZone`), size-based (`NonZeroU64`), and combined rotation with global segment count retention (`max_log_files`). +* Delegates asynchronous buffering to `logforth-append-async` rather than bundling a dedicated worker thread. -* Rolling files based on file size and/or time. -* Drop non-blocking glue in favor of a dedicated async appender combinator. -* Different log file naming and rolling over strategies. +Design references: -Design reference: - -* https://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy -* https://logging.apache.org/log4j/2.x/manual/appenders/rolling-file.html +* Apache Log4j 2 [`DirectWriteRolloverStrategy`](https://logging.apache.org/log4j/2.x/manual/appenders/rolling-file.html) +* Logback [`SizeAndTimeBasedRollingPolicy`](https://logback.qos.ch/manual/appenders.html#SizeAndTimeBasedRollingPolicy) +* Go [`lumberjack`](https://github.com/natefinch/lumberjack) diff --git a/appenders/file/src/append.rs b/appenders/file/src/append.rs index e5f1bdd..54ecadd 100644 --- a/appenders/file/src/append.rs +++ b/appenders/file/src/append.rs @@ -30,9 +30,10 @@ use crate::rolling::RollingFileWriter; use crate::rolling::RollingFileWriterBuilder; use crate::rotation::Rotation; -/// Configures the directory, segment names, rotation, and retention of a [`File`] appender. +/// Builder for creating [`File`] appenders. /// -/// See the [crate documentation](super) for usage examples. +/// Construct a builder with [`FileBuilder::new`], optionally configure layout, suffix, rotation, +/// and retention settings, and finalize with [`build`](Self::build). #[derive(Debug)] pub struct FileBuilder { builder: RollingFileWriterBuilder, @@ -40,11 +41,11 @@ pub struct FileBuilder { } impl FileBuilder { - /// Append to `filename` in `basedir`, creating the directory as needed. Rotation is disabled by - /// default. + /// Creates a builder for log files named `filename` in `basedir`. /// - /// The filename is used literally. Use `FileBuilder::new(dir, "my_app").filename_suffix("log")` - /// to place the period and sequence before the extension, as in `my_app.2026-11-25.1.log`. + /// Rotation is disabled by default. `filename` is used as a literal stem; pass an extension + /// via [`filename_suffix`](Self::filename_suffix) so period and sequence fields appear before + /// the extension (for example, `FileBuilder::new(dir, "my_app").filename_suffix("log")`). pub fn new(basedir: impl Into, filename: impl Into) -> Self { Self { builder: RollingFileWriterBuilder::new(basedir, filename), @@ -52,93 +53,95 @@ impl FileBuilder { } } - /// Build the [`File`] appender. - /// - /// # Errors - /// - /// Returns an error for an invalid filename or suffix, an unrepresentable rotation period, or - /// an I/O failure while preparing the directory or opening the initial file. - pub fn build(self) -> Result { - let FileBuilder { builder, layout } = self; - let writer = builder.build()?; - Ok(File::new(writer, layout)) + /// Sets the layout used to format each log record before appending a trailing newline + /// (default: [`PlainTextLayout`]). + pub fn layout(mut self, layout: impl Into>) -> Self { + self.layout = layout.into(); + self } - /// Set the layout for the logs. - /// - /// Default to [`PlainTextLayout`]. - /// - /// # Examples + /// Sets the filename suffix appended after any period and sequence fields. /// - /// ``` - /// use logforth_append_file::FileBuilder; - /// use logforth_layout_json::JsonLayout; - /// - /// let builder = FileBuilder::new("my_service", "my_app"); - /// builder.layout(JsonLayout::default()); - /// ``` - pub fn layout(mut self, layout: impl Into>) -> Self { - self.layout = layout.into(); + /// At most one leading `.` is stripped, and an empty string clears a previously configured + /// suffix. + pub fn filename_suffix(mut self, suffix: impl Into) -> Self { + self.builder = self.builder.filename_suffix(suffix); self } - /// Set the rotation strategy to roll over log files minutely. + /// Configures time-based rotation at the start of each minute in the configured + /// [`timezone`](Self::timezone). pub fn rollover_minutely(mut self) -> Self { self.builder = self.builder.rotation(Rotation::Minutely); self } - /// Set the rotation strategy to roll over log files hourly. + /// Configures time-based rotation at the start of each hour in the configured + /// [`timezone`](Self::timezone). pub fn rollover_hourly(mut self) -> Self { self.builder = self.builder.rotation(Rotation::Hourly); self } - /// Roll over at the start of each day in the configured timezone. + /// Configures time-based rotation at the start of each calendar day (`00:00`) in the + /// configured [`timezone`](Self::timezone). pub fn rollover_daily(mut self) -> Self { self.builder = self.builder.rotation(Rotation::Daily); self } - /// Set the timezone used for rotation boundaries and segment names. Defaults to the system - /// timezone. + /// Sets the timezone used for time-based rotation boundaries and period filenames + /// (default: [`TimeZone::system()`]). pub fn timezone(mut self, tz: TimeZone) -> Self { self.builder = self.builder.timezone(tz); self } - /// Roll over before a record would exceed the given size in bytes, including its trailing - /// newline. + /// Configures size-based rotation before a formatted record (including its trailing newline) + /// would cause the active segment to exceed `n` bytes. /// - /// A single oversized record is written whole to an empty segment. Sequence numbers increase - /// while the period stays active. On entering another period, numbering starts at 1 and - /// skips existing names. + /// A single record larger than `n` bytes is written whole to an empty segment without rotating + /// again beforehand. Segments are numbered in ascending order starting from `1` within each + /// rotation period. pub fn rollover_size(mut self, n: NonZeroU64) -> Self { self.builder = self.builder.max_file_size(n); self } - /// Add a suffix after all rotation fields. A single leading dot is stripped and an empty input - /// clears the suffix. - pub fn filename_suffix(mut self, suffix: impl Into) -> Self { - self.builder = self.builder.filename_suffix(suffix); - self - } - - /// Keep at most `n` matching files across all periods, including the active file. + /// Sets the maximum number of matching log files retained across all periods, including the + /// active segment. /// - /// With rotation enabled, the oldest inactive segments are pruned at startup and after - /// rollover. By default all segments are retained. + /// By default, all segments are retained. With rotation enabled, excess inactive segments are + /// removed on a best-effort basis during [`build`](Self::build) and pruned on each rollover; + /// the active segment is never removed. pub fn max_log_files(mut self, n: NonZeroUsize) -> Self { self.builder = self.builder.max_log_files(n); self } + + /// Validates the builder configuration, creates `basedir` if needed, and opens the initial log + /// file. + /// + /// # Errors + /// + /// Returns an [`Error`] if: + /// * `filename` is empty, `.`, `..`, or contains `/`, `\`, or `\0`. + /// * `filename_suffix` (after stripping at most one leading `.`) is `.`, `..`, or contains `/`, + /// `\`, or `\0`. + /// * The initial rotation period cannot be represented in `jiff`. + /// * Creating `basedir`, scanning existing segments, or opening the initial segment file fails. + pub fn build(self) -> Result { + let FileBuilder { builder, layout } = self; + let writer = builder.build()?; + Ok(File::new(writer, layout)) + } } -/// Appends each formatted record and a newline directly to the active file. +/// A file appender that writes formatted log records to a single file or rotating segment files. /// -/// If opening the next segment fails, the appender writes the record to the current file and -/// returns the rollover error if the write succeeds. It waits one second before retrying rotation. +/// Each record is formatted with the configured [`Layout`], terminated with `\n`, and written to +/// an append-mode file. See the [crate documentation](crate) for segment naming, retention, and +/// rollover error semantics. #[derive(Debug)] pub struct File { writer: Mutex, diff --git a/appenders/file/src/lib.rs b/appenders/file/src/lib.rs index 22414d5..2ab74d0 100644 --- a/appenders/file/src/lib.rs +++ b/appenders/file/src/lib.rs @@ -12,55 +12,71 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Append log records directly to a single file or to rotating segments. +//! File appender for writing log records to a single file or rotating segment files. //! -//! With `FileBuilder::new(dir, "my_app").filename_suffix("log")`, the filename depends on the -//! rotation policy. +//! [`File`] formats each record with a configured [`Layout`](logforth_core::Layout), appends a +//! trailing newline, and writes directly to an append-mode file. Construct an instance with +//! [`FileBuilder`]. //! -//! | Policy | Example filename | -//! | :-------------- | :--------------------------- | -//! | No rotation | `my_app.log` | -//! | Daily | `my_app.2026-11-25.log` | -//! | Size | `my_app.1.log` | -//! | Hourly and size | `my_app.2026-11-25-17.1.log` | +//! # Segment naming //! -//! Hourly periods include the hour and minutely periods also include the minute, both with two -//! digits. [`FileBuilder::timezone`] selects the timezone for these periods and defaults to the -//! system timezone. The filename is a literal stem. Passing `"my_app.log"` as the stem puts -//! rotation fields after `.log`. +//! Given `FileBuilder::new(dir, "my_app").filename_suffix("log")`, segment filenames depend on the +//! configured rotation policy: //! -//! [`FileBuilder::rollover_size`] numbers segments from 1 within each period. Files keep the same -//! name throughout their lifetime. On startup, the highest numbered segment in the current period -//! is reused if it has room. [`FileBuilder::max_log_files`] limits the total number of matching -//! files across all periods, including the active file. +//! | Policy | Example filename | +//! | :-------------- | :------------------------------ | +//! | No rotation | `my_app.log` | +//! | Minutely | `my_app.2026-11-25-17-05.log` | +//! | Hourly | `my_app.2026-11-25-17.log` | +//! | Daily | `my_app.2026-11-25.log` | +//! | Size | `my_app.1.log` | +//! | Hourly and size | `my_app.2026-11-25-17.1.log` | //! -//! # Example +//! * `filename` is treated as a literal stem. Configure an extension via +//! [`FileBuilder::filename_suffix`] so period and sequence fields appear before the extension. +//! * [`FileBuilder::timezone`] selects the timezone used for rotation boundaries and period fields +//! (default: [`TimeZone::system()`](jiff::tz::TimeZone::system)). +//! * Segment files keep their initial name for their entire lifetime and are never renamed on +//! rollover. +//! * [`FileBuilder::rollover_size`] numbers segments in ascending order starting from `1` (oldest) +//! within each period. On startup, [`FileBuilder::build`] resumes the highest-numbered segment in +//! the active period if its size is below the limit, or opens the next sequence number. +//! +//! # Retention and error handling +//! +//! * [`FileBuilder::max_log_files`] limits the total number of matching regular files across all +//! periods, including the active segment. Non-matching files, directories, symlinks, and the +//! active segment itself are never removed. +//! * If opening the next segment or pruning old segments fails at runtime, [`File`] records a +//! `1`-second retry cooldown, appends the current record to the active segment, and returns the +//! rollover or cleanup [`Error`](logforth_core::Error). +//! +//! # Examples //! //! ``` //! use std::num::NonZeroU64; //! use std::num::NonZeroUsize; //! -//! use jiff::tz::TimeZone; //! use logforth_append_file::FileBuilder; +//! use logforth_append_file::jiff::tz::TimeZone; //! use logforth_core::record::LevelFilter; //! use logforth_layout_json::JsonLayout; //! -//! # fn configure(dir: &std::path::Path) -> Result<(), Box> { -//! let rolling = FileBuilder::new(dir, "my_app") +//! # let temp_dir = tempfile::tempdir()?; +//! # let log_dir = temp_dir.path(); +//! let file = FileBuilder::new(log_dir, "my_app") //! .filename_suffix("log") //! .layout(JsonLayout::default()) //! .rollover_daily() //! .timezone(TimeZone::UTC) -//! .rollover_size(NonZeroU64::try_from(1024 * 1024)?) -//! .max_log_files(NonZeroUsize::try_from(7)?) +//! .rollover_size(NonZeroU64::new(10 * 1024 * 1024).unwrap()) +//! .max_log_files(NonZeroUsize::new(7).unwrap()) //! .build()?; //! //! let logger = logforth_core::builder() -//! .dispatch(|d| d.filter(LevelFilter::All).append(rolling)) +//! .dispatch(|d| d.filter(LevelFilter::All).append(file)) //! .build(); -//! # Ok(()) -//! # } -//! # configure(tempfile::tempdir()?.path())?; +//! # drop(logger); //! # Ok::<(), Box>(()) //! ``` From 55a221b7a59afbbf6d3da9e9ea8285a7a553f89e Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 21:13:22 +0800 Subject: [PATCH 4/4] test(append-file): separate black-box contract tests from white-box clock tests Move public-API behavior and regression tests into `appenders/file/tests/file_test.rs` so input validation, pre-write size boundaries (including trailing newline framing), retention ordering, non-matching entry preservation, append-after-truncation, and sequence exhaustion are exercised end-to-end through `FileBuilder` and `File`. Keep `src/` unit tests strictly for scenarios requiring private access (`Clock::ManualClock` in `rolling.rs` and `Rotation::period_at` in `rotation.rs`), asserting observable file and error outcomes rather than internal helper predicates. Signed-off-by: tison --- appenders/file/src/rolling.rs | 192 +++-------------- appenders/file/tests/file_test.rs | 244 ++++++++++++++++++++++ appenders/file/tests/global_file_limit.rs | 73 ------- 3 files changed, 272 insertions(+), 237 deletions(-) create mode 100644 appenders/file/tests/file_test.rs delete mode 100644 appenders/file/tests/global_file_limit.rs diff --git a/appenders/file/src/rolling.rs b/appenders/file/src/rolling.rs index 42cfaac..574a5ad 100644 --- a/appenders/file/src/rolling.rs +++ b/appenders/file/src/rolling.rs @@ -428,83 +428,6 @@ mod tests { builder } - #[test] - fn validates_names_before_creating_the_directory() { - let dir = tempdir().unwrap(); - let path = dir.path().join("new"); - for stem in ["", ".", "..", "/logs", "a/b", "a\\b", "a\0b"] { - assert!( - RollingFileWriterBuilder::new(&path, stem).build().is_err(), - "{stem:?}" - ); - } - for suffix in [".", "..", "...", "a/b", "a\\b", "a\0b"] { - assert!( - RollingFileWriterBuilder::new(&path, "app") - .filename_suffix(suffix) - .build() - .is_err(), - "{suffix:?}" - ); - } - assert!(!path.exists()); - #[cfg(windows)] - assert!(validate_component("filename", "C:relative").is_err()); - - for (suffix, name) in [("", "app"), (".log", "app.log"), ("..log", "app..log")] { - let mut writer = RollingFileWriterBuilder::new(&path, "app") - .filename_suffix(suffix) - .build() - .unwrap(); - writer.write_all(b"record").unwrap(); - assert_eq!(fs::read(path.join(name)).unwrap(), b"record"); - } - } - - #[test] - fn size_retention_only_deletes_canonical_regular_files() { - let dir = tempdir().unwrap(); - let unrelated = [ - "my_applog", - "my_appXlog", - "my_app2.log", - "my_app.01.log", - "my_app.log", - "my_app.0.log", - "my_app.+1.log", - "my_app.18446744073709551616.log", - "my_app.1log", - "my_app.2026-11-25.log", - "my_app.2026-11-25.1.log", - ]; - for name in unrelated { - fs::write(dir.path().join(name), b"keep").unwrap(); - } - fs::create_dir(dir.path().join("my_app.3.log")).unwrap(); - #[cfg(unix)] - std::os::unix::fs::symlink("my_app.log", dir.path().join("my_app.4.log")).unwrap(); - for seq in [1, 2, 10] { - fs::write(dir.path().join(format!("my_app.{seq}.log")), b"full").unwrap(); - } - let mut writer = RollingFileWriterBuilder::new(dir.path(), "my_app") - .filename_suffix("log") - .max_file_size(NonZeroU64::MIN) - .max_log_files(NonZeroUsize::MIN) - .build() - .unwrap(); - writer.write_all(b"new").unwrap(); - assert_eq!(fs::read(dir.path().join("my_app.11.log")).unwrap(), b"new"); - for seq in [1, 2, 10] { - assert!(!dir.path().join(format!("my_app.{seq}.log")).exists()); - } - for name in unrelated { - assert_eq!(fs::read(dir.path().join(name)).unwrap(), b"keep", "{name}"); - } - assert!(dir.path().join("my_app.3.log").is_dir()); - #[cfg(unix)] - assert!(dir.path().join("my_app.4.log").is_symlink()); - } - #[test] fn time_retention_recognizes_only_the_configured_period_format() { for (rotation, valid, invalid) in [ @@ -540,39 +463,6 @@ mod tests { } } - #[test] - fn checks_size_before_writing_and_keeps_oversized_records_whole() { - let dir = tempdir().unwrap(); - let mut writer = RollingFileWriterBuilder::new(dir.path(), "app") - .max_file_size(NonZeroU64::new(5).unwrap()) - .build() - .unwrap(); - for record in [ - b"oversized".as_slice(), - b"abc", - b"de", - b"1234", - b"xy", - b"another oversized", - ] { - writer.write_all(record).unwrap(); - } - let expected = [ - b"oversized".as_slice(), - b"abcde", - b"1234", - b"xy", - b"another oversized", - ]; - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), expected.len()); - for (i, contents) in expected.into_iter().enumerate() { - assert_eq!( - fs::read(dir.path().join(format!("app.{}", i + 1))).unwrap(), - contents - ); - } - } - #[test] fn restart_resumes_only_the_highest_segment_in_the_current_period() { let dir = tempdir().unwrap(); @@ -611,26 +501,6 @@ mod tests { ); } - #[test] - fn sequence_exhaustion_preserves_the_full_segment() { - let dir = tempdir().unwrap(); - let path = dir.path().join(format!("my_app.{}", u64::MAX)); - fs::write(&path, b"x").unwrap(); - let err = RollingFileWriterBuilder::new(dir.path(), "my_app") - .max_file_size(NonZeroU64::MIN) - .build() - .unwrap_err(); - assert_eq!( - err.source() - .unwrap() - .downcast_ref::() - .unwrap() - .kind(), - io::ErrorKind::AlreadyExists - ); - assert_eq!(fs::read(path).unwrap(), b"x"); - } - #[test] fn collision_on_return_to_a_period_preserves_existing_segments() { let dir = tempdir().unwrap(); @@ -688,8 +558,6 @@ mod tests { let mut writer = b.build().unwrap(); writer.write_all(b"EDT ").unwrap(); writer.clock = Clock::ManualClock("2026-11-01T01:00:00-05:00".parse().unwrap()); - assert!(writer.should_rotate(writer.clock.now(), 3)); - assert!(!writer.rotate_if_needed(writer.clock.now(), 3).unwrap()); writer.write_all(b"EST").unwrap(); writer.clock = Clock::ManualClock("2026-11-01T02:00:00-05:00".parse().unwrap()); writer.write_all(b"later").unwrap(); @@ -714,39 +582,54 @@ mod tests { let mut writer = builder(&dir, Rotation::Minutely, "2026-11-25T17:00:59Z") .build() .unwrap(); - let current = dir.path().join("my_app.2026-11-25-17-00.log"); - let next = dir.path().join("my_app.2026-11-25-17-01.log"); + let initial = dir.path().join("my_app.2026-11-25-17-00.log"); + let blocked = dir.path().join("my_app.2026-11-25-17-02.log"); + let rolled_back = dir.path().join("my_app.2026-11-25-17-01.log"); writer.write_all(b"first ").unwrap(); let permissions = fs::metadata(dir.path()).unwrap().permissions(); fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap(); // Privileged test runners can still create files here. In that case the directory // at the candidate path prevents opening it for append. - let blocker = fs::create_dir(&next); - writer.clock = Clock::ManualClock("2026-11-25T17:01:00Z".parse().unwrap()); + let blocker = fs::create_dir(&blocked); + writer.clock = Clock::ManualClock("2026-11-25T17:02:00Z".parse().unwrap()); let result = writer.write_all(b"failed "); fs::set_permissions(dir.path(), permissions).unwrap(); let err = result.unwrap_err(); let cause = err.source().unwrap().downcast_ref::().unwrap(); match blocker { - Ok(()) => fs::remove_dir(&next).unwrap(), + Ok(()) => fs::remove_dir(&blocked).unwrap(), Err(e) => { assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); assert_eq!(cause.kind(), io::ErrorKind::PermissionDenied); } } - assert_eq!(fs::read(¤t).unwrap(), b"first failed "); + assert_eq!(fs::read(&initial).unwrap(), b"first failed "); - writer.clock = Clock::ManualClock("2026-11-25T17:01:00.999Z".parse().unwrap()); + writer.clock = Clock::ManualClock("2026-11-25T17:02:00.999Z".parse().unwrap()); writer.write_all(b"cooldown").unwrap(); - assert!(!next.exists()); + assert!(!blocked.exists()); + // Stepping the wall clock backward before the failure timestamp exits cooldown immediately. - writer.clock = Clock::ManualClock("2026-11-25T16:59:00Z".parse().unwrap()); - assert!(writer.should_rotate(writer.clock.now(), 1)); - writer.clock = Clock::ManualClock("2026-11-25T17:01:01Z".parse().unwrap()); + writer.clock = Clock::ManualClock("2026-11-25T17:01:30Z".parse().unwrap()); + writer.write_all(b"back").unwrap(); + assert_eq!(fs::read(&rolled_back).unwrap(), b"back"); + + // Re-trigger cooldown on `blocked`, then advance 1 second to verify normal expiry. + let permissions = fs::metadata(dir.path()).unwrap().permissions(); + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap(); + let blocker = fs::create_dir(&blocked); + writer.clock = Clock::ManualClock("2026-11-25T17:02:00Z".parse().unwrap()); + let _ = writer.write_all(b" retry_wait"); + fs::set_permissions(dir.path(), permissions).unwrap(); + if blocker.is_ok() { + fs::remove_dir(&blocked).unwrap(); + } + writer.clock = Clock::ManualClock("2026-11-25T17:02:01Z".parse().unwrap()); writer.write_all(b"retried").unwrap(); - assert_eq!(fs::read(current).unwrap(), b"first failed cooldown"); - assert_eq!(fs::read(next).unwrap(), b"retried"); + assert_eq!(fs::read(initial).unwrap(), b"first failed cooldown"); + assert_eq!(fs::read(rolled_back).unwrap(), b"back retry_wait"); + assert_eq!(fs::read(blocked).unwrap(), b"retried"); } #[test] @@ -763,23 +646,4 @@ mod tests { b"still here" ); } - - #[test] - fn append_after_external_truncation_starts_at_the_new_end() { - let dir = tempdir().unwrap(); - for size in [None, NonZeroU64::new(100)] { - let mut builder = RollingFileWriterBuilder::new(dir.path(), "typed.log"); - builder.files.max_size = size; - let mut writer = builder.build().unwrap(); - let path = dir.path().join(if size.is_some() { - "typed.log.1" - } else { - "typed.log" - }); - writer.write_all(b"original record").unwrap(); - fs::write(&path, b"x").unwrap(); - writer.write_all(b"y").unwrap(); - assert_eq!(fs::read(path).unwrap(), b"xy"); - } - } } diff --git a/appenders/file/tests/file_test.rs b/appenders/file/tests/file_test.rs new file mode 100644 index 0000000..8998ed3 --- /dev/null +++ b/appenders/file/tests/file_test.rs @@ -0,0 +1,244 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::error::Error as _; +use std::fs; +use std::io; +use std::num::NonZeroU64; +use std::num::NonZeroUsize; + +use logforth_append_file::FileBuilder; +use logforth_append_file::jiff::tz::TimeZone; +use logforth_core::Append; +use logforth_core::Diagnostic; +use logforth_core::Error; +use logforth_core::Layout; +use logforth_core::record::Record; +use tempfile::tempdir; + +#[derive(Debug)] +struct PayloadLayout; + +impl Layout for PayloadLayout { + fn format(&self, record: &Record, _: &[Box]) -> Result, Error> { + Ok(record.payload().to_string().into_bytes()) + } +} + +fn append_str(appender: &impl Append, text: &str) -> Result<(), Error> { + appender.append( + &Record::builder().payload(format_args!("{text}")).build(), + &[], + ) +} + +#[test] +fn validates_filename_and_suffix_before_creating_directory() { + let dir = tempdir().unwrap(); + let path = dir.path().join("new_logs"); + + let invalid_stems = [ + "", + ".", + "..", + "/logs", + "a/b", + "a\\b", + "a\0b", + #[cfg(windows)] + "C:relative", + ]; + + for stem in invalid_stems { + assert!( + FileBuilder::new(&path, stem).build().is_err(), + "stem {stem:?} should be rejected" + ); + } + for suffix in [".", "..", "...", "a/b", "a\\b", "a\0b"] { + assert!( + FileBuilder::new(&path, "app") + .filename_suffix(suffix) + .build() + .is_err(), + "suffix {suffix:?} should be rejected" + ); + } + assert!(!path.exists()); + + for (suffix, expected_name) in [("", "app"), (".log", "app.log"), ("..log", "app..log")] { + let appender = FileBuilder::new(&path, "app") + .filename_suffix(suffix) + .layout(PayloadLayout) + .build() + .unwrap(); + append_str(&appender, "record").unwrap(); + appender.flush().unwrap(); + assert_eq!(fs::read(path.join(expected_name)).unwrap(), b"record\n"); + } +} + +#[test] +fn checks_size_before_writing_including_newline_and_keeps_oversized_records_whole() { + let dir = tempdir().unwrap(); + let appender = FileBuilder::new(dir.path(), "app") + .layout(PayloadLayout) + .rollover_size(NonZeroU64::new(6).unwrap()) + .build() + .unwrap(); + + for payload in ["oversized", "ab", "cd", "1234", "xy", "another oversized"] { + append_str(&appender, payload).unwrap(); + } + + let expected = [ + b"oversized\n".as_slice(), + b"ab\ncd\n", + b"1234\n", + b"xy\n", + b"another oversized\n", + ]; + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), expected.len()); + for (i, contents) in expected.into_iter().enumerate() { + assert_eq!( + fs::read(dir.path().join(format!("app.{}", i + 1))).unwrap(), + contents + ); + } +} + +#[test] +fn size_retention_prunes_oldest_numeric_segments_and_ignores_non_matching_entries() { + let dir = tempdir().unwrap(); + let unrelated = [ + "my_applog", + "my_appXlog", + "my_app2.log", + "my_app.01.log", + "my_app.log", + "my_app.0.log", + "my_app.+1.log", + "my_app.18446744073709551616.log", + "my_app.1log", + "my_app.2026-11-25.log", + "my_app.2026-11-25.1.log", + ]; + for name in unrelated { + fs::write(dir.path().join(name), b"keep").unwrap(); + } + fs::create_dir(dir.path().join("my_app.3.log")).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink("my_app.log", dir.path().join("my_app.4.log")).unwrap(); + + for seq in [1, 2, 10] { + fs::write(dir.path().join(format!("my_app.{seq}.log")), b"full").unwrap(); + } + + let appender = FileBuilder::new(dir.path(), "my_app") + .filename_suffix("log") + .layout(PayloadLayout) + .rollover_size(NonZeroU64::MIN) + .max_log_files(NonZeroUsize::new(2).unwrap()) + .build() + .unwrap(); + + append_str(&appender, "eleven").unwrap(); + append_str(&appender, "twelve").unwrap(); + + for seq in [1, 2, 10] { + assert!(!dir.path().join(format!("my_app.{seq}.log")).exists()); + } + assert_eq!( + fs::read(dir.path().join("my_app.11.log")).unwrap(), + b"eleven\n" + ); + assert_eq!( + fs::read(dir.path().join("my_app.12.log")).unwrap(), + b"twelve\n" + ); + for name in unrelated { + assert_eq!(fs::read(dir.path().join(name)).unwrap(), b"keep", "{name}"); + } + assert!(dir.path().join("my_app.3.log").is_dir()); + #[cfg(unix)] + assert!(dir.path().join("my_app.4.log").is_symlink()); +} + +#[test] +fn startup_retention_applies_limit_across_multiple_periods() { + let dir = tempdir().unwrap(); + for name in [ + "test.2000-01-01.10", + "test.2000-01-02.2", + "test.2000-01-02.10", + ] { + fs::write(dir.path().join(name), name).unwrap(); + } + + let _appender = FileBuilder::new(dir.path(), "test") + .rollover_daily() + .timezone(TimeZone::UTC) + .rollover_size(NonZeroU64::MIN) + .max_log_files(NonZeroUsize::new(2).unwrap()) + .build() + .unwrap(); + + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); + assert!(!dir.path().join("test.2000-01-01.10").exists()); + assert!(!dir.path().join("test.2000-01-02.2").exists()); + assert!(dir.path().join("test.2000-01-02.10").is_file()); +} + +#[test] +fn append_mode_writes_at_eof_after_external_truncation() { + let dir = tempdir().unwrap(); + for size in [None, NonZeroU64::new(100)] { + let mut builder = FileBuilder::new(dir.path(), "typed.log").layout(PayloadLayout); + if let Some(max) = size { + builder = builder.rollover_size(max); + } + let appender = builder.build().unwrap(); + let path = dir.path().join(if size.is_some() { + "typed.log.1" + } else { + "typed.log" + }); + + append_str(&appender, "original record").unwrap(); + fs::write(&path, b"x").unwrap(); + append_str(&appender, "y").unwrap(); + assert_eq!(fs::read(path).unwrap(), b"xy\n"); + } +} + +#[test] +fn sequence_exhaustion_preserves_existing_segment_and_returns_single_layer_error() { + let dir = tempdir().unwrap(); + let path = dir.path().join(format!("my_app.{}", u64::MAX)); + fs::write(&path, b"x").unwrap(); + + let err = FileBuilder::new(dir.path(), "my_app") + .rollover_size(NonZeroU64::MIN) + .build() + .unwrap_err(); + assert_eq!( + err.source() + .unwrap() + .downcast_ref::() + .unwrap() + .kind(), + io::ErrorKind::AlreadyExists + ); + assert_eq!(fs::read(path).unwrap(), b"x"); +} diff --git a/appenders/file/tests/global_file_limit.rs b/appenders/file/tests/global_file_limit.rs deleted file mode 100644 index 5e1724a..0000000 --- a/appenders/file/tests/global_file_limit.rs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2024 FastLabs Developers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use std::fs; -use std::num::NonZeroU64; -use std::num::NonZeroUsize; - -use jiff::tz::TimeZone; -use logforth_append_file::FileBuilder; -use logforth_core::Append; -use logforth_core::record::Record; -use tempfile::tempdir; - -#[test] -fn size_limit_retains_the_newest_segments_in_numeric_order() { - let dir = tempdir().unwrap(); - let appender = FileBuilder::new(dir.path(), "test") - .filename_suffix("log") - .rollover_size(NonZeroU64::MIN) - .max_log_files(NonZeroUsize::new(3).unwrap()) - .build() - .unwrap(); - - for i in 1..=12 { - appender - .append( - &Record::builder().payload(format_args!("entry {i}")).build(), - &[], - ) - .unwrap(); - } - appender.flush().unwrap(); - - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 3); - for i in 10..=12 { - let record = fs::read_to_string(dir.path().join(format!("test.{i}.log"))).unwrap(); - assert!(record.ends_with(&format!("entry {i}\n"))); - } -} - -#[test] -fn startup_applies_one_limit_across_periods() { - let dir = tempdir().unwrap(); - for name in [ - "test.2000-01-01.10", - "test.2000-01-02.2", - "test.2000-01-02.10", - ] { - fs::write(dir.path().join(name), name).unwrap(); - } - - let _appender = FileBuilder::new(dir.path(), "test") - .rollover_daily() - .timezone(TimeZone::UTC) - .rollover_size(NonZeroU64::MIN) - .max_log_files(NonZeroUsize::new(2).unwrap()) - .build() - .unwrap(); - - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); - assert!(dir.path().join("test.2000-01-02.10").is_file()); -}