Skip to main content

RotatingFile

Struct RotatingFile 

Source
pub struct RotatingFile { /* private fields */ }
Available on crate feature std only.
Expand description

A file writer that rotates by size and/or time.

The active file is always at the configured path. On rotation it is renamed to <path>.1, an existing <path>.1 becomes <path>.2, and so on; the file that would move past <path>.<max_files> is deleted. With max_files(0) the active file is deleted at rotation instead of kept.

Rotation happens between records, never inside one: the size check runs before each write call, and the built-in sinks write a whole record per call. A record larger than max_bytes is written to a fresh file on its own.

Use it as the writer of a super::WriterSink (aliased as super::RotatingFileSink) or of a super::NonBlocking sink. Behind a NonBlocking sink, records reach this writer in batches through the worker’s write buffer (64 KiB by default), so a file can exceed max_bytes by up to that buffer size and period boundaries are honoured per batch; set the worker’s buffer_capacity(0) for per-record precision.

§Failed rotation

The current file handle is flushed and closed before any rename, so rotation works on Windows as well as Unix. A rotation is all or nothing:

  1. the active file is moved to <path>.rotating. If that fails (on Windows, typically because another process holds the file open without delete sharing), nothing else has been touched;
  2. the history is shifted up one slot, the oldest file going to <path>.pruning rather than being deleted;
  3. <path>.rotating becomes <path>.1, and only then is <path>.pruning deleted.

If a rename in steps 2-3 fails, the renames already done are undone in reverse order. So a failed rotation never deletes or overwrites rotated history: every rotated file keeps its name and content. The writer then reopens the active file, keeps appending to it, retries after another max_bytes or at the next period, and reports the error from the next Write::flush call (which the logger passes to its error handler).

If an undo fails as well (a second fault, for example the directory becoming read-only mid-rotation), the rollback stops and the files keep whatever names they have at that point; still nothing is deleted. Records that were in the active file stay in <path>.rotating, the writer starts a new active file, and every later rotation attempt fails with io::ErrorKind::AlreadyExists naming that file (so it is never overwritten) until an operator moves it aside.

§Examples

use log_io::format::JsonFormat;
use log_io::sink::{RotatingFile, Rotation};
use log_io::{Level, Logger};

let file = RotatingFile::builder("logs/app.jsonl")
    .max_bytes(50 * 1024 * 1024)
    .rotation(Rotation::Daily)
    .max_files(14)
    .open()?;
let logger = Logger::builder().level(Level::Info).writer(file, JsonFormat::new()).build();

Implementations§

Source§

impl RotatingFile

Source

pub fn builder(path: impl AsRef<Path>) -> RotatingFileBuilder

Start configuring a rotating file at path. Defaults: no size limit, Rotation::Never, keep 5 rotated files, 8 KiB buffer.

Source

pub fn path(&self) -> &Path

The path of the active file.

Source

pub fn current_size(&self) -> u64

Bytes written to the active file so far (including bytes that existed when it was opened).

Source

pub fn rotate_now(&mut self) -> Result<()>

Rotate immediately, regardless of size and time.

§Errors

Returns the I/O error from flushing, renaming, or reopening. On error the writer keeps appending to the active file.

Trait Implementations§

Source§

impl Debug for RotatingFile

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for RotatingFile

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Write for RotatingFile

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
1.36.0 · Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize, Error>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
1.0.0 · Source§

fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Writes a formatted string into this writer, returning any error encountered. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.