Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
480 changes: 480 additions & 0 deletions CHANGELOG-OLD.md

Large diffs are not rendered by default.

498 changes: 20 additions & 478 deletions CHANGELOG.md

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
1 change: 0 additions & 1 deletion appenders/file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ logforth-core = { workspace = true }

[dev-dependencies]
logforth-layout-json = { workspace = true }
rand = { workspace = true }
tempfile = { workspace = true }

[lints]
Expand Down
17 changes: 8 additions & 9 deletions appenders/file/README.md
Original file line number Diff line number Diff line change
@@ -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)
117 changes: 66 additions & 51 deletions appenders/file/src/append.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -28,98 +30,118 @@ use crate::rolling::RollingFileWriter;
use crate::rolling::RollingFileWriterBuilder;
use crate::rotation::Rotation;

/// A builder to configure and create an [`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,
layout: Box<dyn Layout>,
}

impl FileBuilder {
/// Create a new file appender builder.
/// Creates a builder for log files named `filename` in `basedir`.
///
/// 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<PathBuf>, filename: impl Into<String>) -> Self {
Self {
builder: RollingFileWriterBuilder::new(basedir, filename),
layout: Box::new(PlainTextLayout::default()),
}
}

/// Build the [`File`] appender.
///
/// # Errors
///
/// Return an error if either:
///
/// * The log directory cannot be created.
/// * The configured filename is empty.
pub fn build(self) -> Result<File, Error> {
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<Box<dyn Layout>>) -> Self {
self.layout = layout.into();
self
}

/// Set the layout for the logs.
///
/// Default to [`PlainTextLayout`].
///
/// # Examples
///
/// ```
/// use logforth_append_file::FileBuilder;
/// use logforth_layout_json::JsonLayout;
/// Sets the filename suffix appended after any period and sequence fields.
///
/// let builder = FileBuilder::new("my_service", "my_app");
/// builder.layout(JsonLayout::default());
/// ```
pub fn layout(mut self, layout: impl Into<Box<dyn Layout>>) -> 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<String>) -> 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
}

/// Set the rotation strategy to roll over log files daily at 00:00 in the local time zone.
/// 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 rotation strategy to roll over log files if the current log file exceeds the given
/// size.
///
/// 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 {
self.builder = self.builder.max_file_size(n);
/// 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
}

/// Set the filename suffix.
pub fn filename_suffix(mut self, suffix: impl Into<String>) -> Self {
self.builder = self.builder.filename_suffix(suffix);
/// Configures size-based rotation before a formatted record (including its trailing newline)
/// would cause the active segment to exceed `n` bytes.
///
/// 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
}

/// Set the maximum number of log files to keep.
/// Sets the maximum number of matching log files retained across all periods, including the
/// active segment.
///
/// 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<File, Error> {
let FileBuilder { builder, layout } = self;
let writer = builder.build()?;
Ok(File::new(writer, layout))
}
}

/// An appender that writes log records to rolling files.
/// A file appender that writes formatted log records to a single file or rotating segment files.
///
/// 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<RollingFileWriter>,
Expand Down Expand Up @@ -150,10 +172,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();
}
}
59 changes: 6 additions & 53 deletions appenders/file/src/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
65 changes: 57 additions & 8 deletions appenders/file/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,79 @@
// 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.
//! File appender for writing log records to a single file or rotating segment files.
//!
//! # Example
//! [`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`].
//!
//! # Segment naming
//!
//! Given `FileBuilder::new(dir, "my_app").filename_suffix("log")`, segment filenames depend on the
//! configured rotation policy:
//!
//! | 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` |
//!
//! * `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 logforth_append_file::File;
//! use logforth_append_file::FileBuilder;
//! use logforth_append_file::jiff::tz::TimeZone;
//! use logforth_core::record::LevelFilter;
//! use logforth_layout_json::JsonLayout;
//!
//! let rolling = FileBuilder::new("logs", "app_log")
//! # 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()
//! .build()
//! .unwrap();
//! .timezone(TimeZone::UTC)
//! .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();
//! # drop(logger);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(missing_docs)]

pub extern crate jiff;

pub use self::append::File;
pub use self::append::FileBuilder;

Expand Down
Loading
Loading