Crates.io | logroller |
lib.rs | logroller |
version | 0.1.2 |
source | src |
created_at | 2024-10-31 15:30:23.815062 |
updated_at | 2024-11-29 15:59:55.292114 |
description | A Rust library for automatic file rotation, working with the `tracing-appender` crate. |
homepage | |
repository | https://github.com/trayvonpan/logroller/ |
max_upload_size | |
id | 1430251 |
size | 53,888 |
LogRoller is a Rust library for efficient log writing and file rotation. It provides a simple API for writing logs to files and automatically rotating them based on size or time. And it works seamlessly with the tracing-appender
crate for use with the tracing
framework.
tracing
framework.Add logroller
to your Cargo.toml
:
[dependencies]
logroller = "0.1"
logroller
as a simple loggerCreate a new LogRoller
instance and write logs to it:
use logroller::{LogRollerBuilder, Rotation, RotationSize};
use std::io::Write;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut logger = LogRollerBuilder::new("./logs", "logger.log")
.rotation(Rotation::SizeBased(RotationSize::KB(256)))
.max_keep_files(3)
.build()?;
writeln!(logger, "This is an info message")?;
writeln!(logger, "This is a warning message")?;
writeln!(logger, "This is an error message")?;
Ok(())
}
logroller
with tracing
and tracing-appender
logroller
can be used as a file appender for the tracing-appender
crate, by enabling the tracing
feature:
[dependencies]
logroller = { version = "0.1", features = ["tracing"] }
tracing-appender
only supports rotating logs according to the UTC time zone. logroller
can rotate logs according to the local time zone.
use logroller::{Compression, LogRollerBuilder, Rotation, RotationAge, TimeZone};
use tracing_subscriber::util::SubscriberInitExt;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let appender = LogRollerBuilder::new("./logs", "tracing.log")
.rotation(Rotation::AgeBased(RotationAge::Minutely))
.max_keep_files(3)
.time_zone(TimeZone::Local)
.compression(Compression::Gzip)
.build()?;
let (non_blocking, _guard) = tracing_appender::non_blocking(appender);
tracing_subscriber::fmt()
.with_writer(non_blocking)
.with_ansi(false)
.with_target(false)
.with_file(true)
.with_line_number(true)
.finish()
.try_init()?;
tracing::info!("This is an info message");
tracing::warn!("This is a warning message");
tracing::error!("This is an error message");
Ok(())
}