Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use jiff for timestamp #40

Merged
merged 8 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
15 changes: 5 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,27 @@ rustdoc-args = ["--cfg", "docs"]

[features]
fastrace = ["dep:fastrace"]
json = ["dep:serde_json", "dep:serde"]
json = ["dep:serde_json", "dep:serde", "jiff/serde"]
no-color = ["colored/no-color"]
opentelemetry = [
"dep:opentelemetry",
"dep:opentelemetry-otlp",
"dep:opentelemetry_sdk",
]
rolling_file = ["dep:crossbeam-channel", "dep:parking_lot", "dep:time"]
rolling_file = ["dep:crossbeam-channel", "dep:parking_lot"]

[dependencies]
anyhow = { version = "1.0" }
colored = { version = "2.1" }
humantime = { version = "2.1" }
jiff = { version = "0.1.5" }
log = { version = "0.4", features = ["std", "kv_unstable"] }
paste = { version = "1.0" }
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }

[dev-dependencies]
rand = "0.8.5"
tempfile = "3.3"
rand = "0.8"
tempfile = "3.12"

## Rolling file dependencies
[dependencies.crossbeam-channel]
Expand All @@ -65,11 +65,6 @@ version = "0.5"
optional = true
version = "0.12"

[dependencies.time]
features = ["formatting", "parsing", "macros"]
optional = true
version = "0.3"

## Fastrace dependencies
[dependencies.fastrace]
optional = true
Expand Down
5 changes: 2 additions & 3 deletions src/append/fastrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::time::SystemTime;

use jiff::Zoned;
use log::Record;

use crate::append::Append;
Expand All @@ -27,7 +26,7 @@ impl Append for FastraceEvent {
fn append(&self, record: &Record) -> anyhow::Result<()> {
let message = format!(
"{} {:>5} {}{}",
humantime::format_rfc3339_micros(SystemTime::now()),
Zoned::now(),
record.level(),
record.args(),
KvDisplay::new(record.key_values()),
Expand Down
1 change: 0 additions & 1 deletion src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ pub use self::opentelemetry::OpentelemetryLog;
pub use self::rolling_file::RollingFile;
pub use self::stdio::Stderr;
pub use self::stdio::Stdout;

use crate::layout::IdenticalLayout;
use crate::layout::Layout;

Expand Down
36 changes: 18 additions & 18 deletions src/append/rolling_file/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use time::OffsetDateTime;
use jiff::Timestamp;

#[derive(Debug)]
pub enum Clock {
Expand All @@ -22,16 +22,16 @@ pub enum Clock {
}

impl Clock {
pub fn now(&self) -> OffsetDateTime {
pub fn now(&self) -> Timestamp {
match self {
Clock::DefaultClock => OffsetDateTime::now_utc(),
Clock::DefaultClock => Timestamp::now(),
#[cfg(test)]
Clock::ManualClock(clock) => clock.now(),
}
}

#[cfg(test)]
pub fn set_now(&mut self, new_time: OffsetDateTime) {
pub fn set_now(&mut self, new_time: Timestamp) {
if let Clock::ManualClock(clock) = self {
clock.set_now(new_time);
}
Expand All @@ -42,38 +42,38 @@ impl Clock {
#[derive(Debug)]
#[cfg(test)]
pub struct ManualClock {
fixed_time: OffsetDateTime,
now: Timestamp,
}

#[cfg(test)]
impl ManualClock {
pub fn new(fixed_time: OffsetDateTime) -> ManualClock {
ManualClock { fixed_time }
pub fn new(now: Timestamp) -> ManualClock {
ManualClock { now }
}

fn now(&self) -> OffsetDateTime {
self.fixed_time
fn now(&self) -> Timestamp {
self.now
}

pub fn set_now(&mut self, new_time: OffsetDateTime) {
self.fixed_time = new_time;
pub fn set_now(&mut self, now: Timestamp) {
self.now = now;
}
}

#[cfg(test)]
mod tests {
use time::macros::datetime;
use std::str::FromStr;

use super::*;

#[test]
fn test_manual_clock_adjusting() {
let mut clock = ManualClock {
fixed_time: datetime!(2023-01-01 12:00:00 UTC),
};
assert_eq!(clock.now(), datetime!(2023-01-01 12:00:00 UTC));
let now = Timestamp::from_str("2023-01-01T12:00:00Z").unwrap();
let mut clock = ManualClock { now };
assert_eq!(clock.now(), now);

clock.set_now(datetime!(2024-01-01 12:00:00 UTC));
assert_eq!(clock.now(), datetime!(2024-01-01 12:00:00 UTC));
let now = Timestamp::from_str("2024-01-01T12:00:00Z").unwrap();
clock.set_now(now);
assert_eq!(clock.now(), now);
}
}
37 changes: 15 additions & 22 deletions src/append/rolling_file/rolling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@ use std::path::Path;
use std::path::PathBuf;

use anyhow::Context;
use jiff::Timestamp;
use parking_lot::RwLock;
use time::format_description;
use time::Date;
use time::OffsetDateTime;

use crate::append::rolling_file::clock::Clock;
use crate::append::rolling_file::Rotation;
Expand Down Expand Up @@ -166,7 +164,7 @@ struct State {
log_dir: PathBuf,
log_filename_prefix: Option<String>,
log_filename_suffix: Option<String>,
date_format: Vec<format_description::FormatItem<'static>>,
date_format: &'static str,
rotation: Rotation,
current_count: usize,
current_filesize: usize,
Expand Down Expand Up @@ -213,11 +211,8 @@ impl State {
Ok((state, writer))
}

fn join_date(&self, date: &OffsetDateTime, cnt: usize) -> String {
let date = date.format(&self.date_format).expect(
"failed to format OffsetDateTime; this is a bug in logforth rolling file appender",
);

fn join_date(&self, date: &Timestamp, cnt: usize) -> String {
let date = date.strftime(self.date_format);
match (
&self.rotation,
&self.log_filename_prefix,
Expand All @@ -235,7 +230,7 @@ impl State {
}
}

fn create_log_writer(&self, now: OffsetDateTime, cnt: usize) -> anyhow::Result<File> {
fn create_log_writer(&self, now: Timestamp, cnt: usize) -> anyhow::Result<File> {
fs::create_dir_all(&self.log_dir).context("failed to create log directory")?;
let filename = self.join_date(&now, cnt);
if let Some(max_files) = self.max_files {
Expand Down Expand Up @@ -280,9 +275,8 @@ impl State {
}
}

if self.log_filename_prefix.is_none()
&& self.log_filename_suffix.is_none()
&& Date::parse(filename, &self.date_format).is_err()
if self.log_filename_prefix.is_none() && self.log_filename_suffix.is_none()
// && Date::parse(filename, &self.date_format).is_err()
{
return None;
}
Expand All @@ -309,7 +303,7 @@ impl State {
Ok(())
}

fn refresh_writer(&self, now: OffsetDateTime, cnt: usize, file: &mut File) {
fn refresh_writer(&self, now: Timestamp, cnt: usize, file: &mut File) {
match self.create_log_writer(now, cnt) {
Ok(new_file) => {
if let Err(err) = file.flush() {
Expand All @@ -321,9 +315,9 @@ impl State {
}
}

fn should_rollover_on_date(&self, date: OffsetDateTime) -> bool {
fn should_rollover_on_date(&self, date: Timestamp) -> bool {
self.next_date_timestamp
.is_some_and(|ts| date.unix_timestamp() as usize >= ts)
.is_some_and(|ts| date.as_millisecond() as usize >= ts)
}

fn should_rollover_on_size(&self) -> bool {
Expand All @@ -336,24 +330,23 @@ impl State {
self.current_count
}

fn advance_date(&mut self, now: OffsetDateTime) {
fn advance_date(&mut self, now: Timestamp) {
self.current_count = 0;
self.current_filesize = 0;
self.next_date_timestamp = self.rotation.next_date_timestamp(&now);
}
}

#[cfg(test)]
mod tests {
use std::cmp::min;
use std::fs;
use std::io::Write;
use std::ops::Add;

use std::time::Duration;
use rand::distributions::Alphanumeric;
use rand::Rng;
use tempfile::TempDir;
use time::macros::datetime;
use time::Duration;

use crate::append::rolling_file::clock::Clock;
use crate::append::rolling_file::clock::ManualClock;
Expand Down Expand Up @@ -487,8 +480,8 @@ mod tests {
) {
let temp_dir = TempDir::new().expect("failed to create a temporary directory");
let max_files = 10;
// Small file size and too many files to ensure both of file size and time rotation can be
// triggered.
// Small file size and too many files to ensure both of file size and time rotation can
be // triggered.
let total_files = 100;
let file_size = 500;

Expand Down
Loading
Loading