Skip to content

Commit 60a90cb

Browse files
committed
Remove time prepending
Callers can add timestamp support as a field during log message formatting.
1 parent 92b526f commit 60a90cb

File tree

2 files changed

+34
-111
lines changed

2 files changed

+34
-111
lines changed

Cargo.toml

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,49 +2,49 @@
22
name = "ftlog"
33
version = "0.2.13"
44
edition = "2021"
5-
authors = [ "Non-convex Tech" ]
5+
authors = ["Non-convex Tech"]
66
license = "MIT OR Apache-2.0"
77
readme = "README.md"
88
repository = "https://github.com/nonconvextech/ftlog"
99
documentation = "https://docs.rs/ftlog"
1010
description = """
1111
An asynchronous logging library for high performance
1212
"""
13-
categories = [ "development-tools::debugging" ]
14-
keywords = [ "logging" ]
15-
exclude = [ ".standard-version", ".versionrc", ".github" ]
13+
categories = ["development-tools::debugging"]
14+
keywords = ["logging"]
15+
exclude = [".standard-version", ".versionrc", ".github"]
1616

1717
[features]
18-
default = [ "random_drop" ]
19-
tsc = [ "minstant", "once_cell" ]
20-
random_drop = [ "fastrand" ]
18+
default = ["random_drop"]
19+
tsc = ["minstant", "once_cell"]
20+
random_drop = ["fastrand"]
2121

2222
[dependencies]
23+
arc-swap = "1"
2324
crossbeam-channel = "0.5.0"
2425
hashbrown = "0.14"
25-
arc-swap = "1"
2626
nohash-hasher = "0.2"
2727
typed-builder = "0.16"
2828

29-
[dependencies.fastrand]
30-
version = "2"
31-
optional = true
29+
[dependencies.fastrand]
30+
version = "2"
31+
optional = true
3232

33-
[dependencies.time]
34-
version = "0.3"
35-
features = [ "local-offset", "formatting" ]
33+
[dependencies.log]
34+
version = "0.4"
35+
features = ["std", "kv_unstable"]
3636

37-
[dependencies.minstant]
38-
version = "0.1"
39-
optional = true
37+
[dependencies.minstant]
38+
version = "0.1"
39+
optional = true
4040

41-
[dependencies.once_cell]
42-
version = "1"
43-
optional = true
41+
[dependencies.once_cell]
42+
version = "1"
43+
optional = true
4444

45-
[dependencies.log]
46-
version = "0.4"
47-
features = [ "std", "kv_unstable" ]
45+
[dependencies.time]
46+
version = "0.3"
47+
features = ["local-offset", "formatting"]
4848

4949
[target."cfg(target_family = \"unix\")".dependencies.tz-rs]
5050
version = "0.6.14"

src/lib.rs

Lines changed: 11 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,6 @@
7676
//! .expire(Duration::days(7))
7777
//! .build(),
7878
//! )
79-
//! // timezone of log message timestamp, use local by default
80-
//! // .local_timezone()
81-
//! // or use fiexed timezone for better throughput, since retrieving timezone is a time consuming operation
82-
//! // this does not affect worker threads (that call log), but can boost log thread performance (higher throughput).
83-
//! .fixed_timezone(time::UtcOffset::current_local_offset().unwrap())
8479
//! // level filter for root appender
8580
//! .root_log_level(LevelFilter::Warn)
8681
//! // write logs in ftlog::appender to "./ftlog-appender.log" instead of "./current.log"
@@ -312,6 +307,7 @@ use tm::{duration, now, to_utc, Time};
312307

313308
#[cfg(not(feature = "tsc"))]
314309
mod tm {
310+
315311
use super::*;
316312

317313
pub type Time = std::time::SystemTime;
@@ -365,7 +361,6 @@ fn local_timezone() -> UtcOffset {
365361
}
366362

367363
struct LogMsg {
368-
time: Time,
369364
msg: Box<dyn Sync + Send + Display>,
370365
level: Level,
371366
target: String,
@@ -382,8 +377,6 @@ impl LogMsg {
382377
root_level: LevelFilter,
383378
missed_log: &mut HashMap<u64, i64, nohash_hasher::BuildNoHashHasher<u64>>,
384379
last_log: &mut HashMap<u64, Time, nohash_hasher::BuildNoHashHasher<u64>>,
385-
offset: Option<UtcOffset>,
386-
time_format: &time::format_description::OwnedFormatItem,
387380
) {
388381
let msg = self.msg.to_string();
389382
if msg.is_empty() {
@@ -408,12 +401,6 @@ impl LogMsg {
408401
root
409402
};
410403

411-
let delay = duration(self.time, now);
412-
let utc_datetime = to_utc(self.time);
413-
414-
let offset_datetime = offset
415-
.map(|o| utc_datetime.to_offset(o))
416-
.unwrap_or(utc_datetime);
417404
let s: String;
418405
if self.limit > 0 {
419406
let missed_entry = missed_log.entry(self.limit_key).or_insert_with(|| 0);
@@ -425,29 +412,10 @@ impl LogMsg {
425412
}
426413
last_log.insert(self.limit_key, now);
427414

428-
s = format!(
429-
"{} {}ms {} {}\n",
430-
offset_datetime
431-
.format(&time_format)
432-
.unwrap_or_else(|_| offset_datetime
433-
.format(&time::format_description::well_known::Rfc3339)
434-
.unwrap()),
435-
delay.as_millis(),
436-
*missed_entry,
437-
msg
438-
);
415+
s = format!("{} {}\n", *missed_entry, msg);
439416
*missed_entry = 0;
440417
} else {
441-
s = format!(
442-
"{} {}ms {}\n",
443-
offset_datetime
444-
.format(&time_format)
445-
.unwrap_or_else(|_| offset_datetime
446-
.format(&time::format_description::well_known::Rfc3339)
447-
.unwrap()),
448-
delay.as_millis(),
449-
msg
450-
);
418+
s = format!("{}\n", msg);
451419
}
452420
if let Err(e) = writer.write_all(s.as_bytes()) {
453421
eprintln!("logger write message failed: {}", e);
@@ -543,6 +511,7 @@ impl FtLogFormat for FtLogFormatter {
543511
#[inline]
544512
fn msg(&self, record: &Record) -> Box<dyn Send + Sync + Display> {
545513
Box::new(Message {
514+
time: now(),
546515
level: record.level(),
547516
thread: std::thread::current().name().map(|n| n.to_string()),
548517
file: record
@@ -561,6 +530,7 @@ impl FtLogFormat for FtLogFormatter {
561530
}
562531

563532
struct Message {
533+
time: Time,
564534
level: Level,
565535
thread: Option<String>,
566536
file: Cow<'static, str>,
@@ -570,8 +540,13 @@ struct Message {
570540

571541
impl Display for Message {
572542
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543+
let utc_datetime = to_utc(self.time);
544+
573545
f.write_str(&format!(
574-
"{} {} [{}:{}] {}",
546+
"{} {} {} [{}:{}] {}",
547+
utc_datetime
548+
.format(&time::format_description::well_known::Rfc3339)
549+
.unwrap(),
575550
self.level,
576551
self.thread.as_deref().unwrap_or(""),
577552
self.file,
@@ -679,7 +654,6 @@ impl Log for Logger {
679654
};
680655
let msg = self.format.msg(record);
681656
let msg = LoggerInput::LogMsg(LogMsg {
682-
time: now(),
683657
msg,
684658
target: record.target().to_owned(),
685659
level: record.level(),
@@ -784,7 +758,6 @@ pub struct Builder {
784758
filters: Vec<Directive>,
785759
drop_filters: Vec<Box<dyn Fn(&Record) -> bool + Send + Sync>>,
786760
bounded_channel_option: Option<BoundedChannelOption>,
787-
timezone: LogTimezone,
788761
}
789762

790763
/// Handy function to get ftlog builder
@@ -834,7 +807,6 @@ impl Builder {
834807
block: false,
835808
print: true,
836809
}),
837-
timezone: LogTimezone::Local,
838810
time_format: None,
839811
}
840812
}
@@ -967,56 +939,11 @@ impl Builder {
967939
self
968940
}
969941

970-
#[inline]
971-
/// Log with timestamp of local timezone
972-
///
973-
/// Timezone is fixed after logger setup for the following reasons:
974-
/// 1. `time` v0.3 currently do not allow access to local offset for multithread process
975-
/// in unix-like OS.
976-
/// 1. timezone retrieval from OS is quite slow (around several microsecond) compare with
977-
/// utc timestamp retrieval (around tens of nanoseconds)
978-
pub fn local_timezone(mut self) -> Builder {
979-
self.timezone = LogTimezone::Local;
980-
self
981-
}
982-
983-
#[inline]
984-
/// Log with timestamp of UTC timezone
985-
pub fn utc(mut self) -> Builder {
986-
self.timezone = LogTimezone::Utc;
987-
self
988-
}
989-
990-
#[inline]
991-
/// Log with timestamp of fixed timezone
992-
pub fn fixed_timezone(mut self, timezone: UtcOffset) -> Builder {
993-
self.timezone = LogTimezone::Fixed(timezone);
994-
self
995-
}
996-
997-
#[inline]
998-
/// Specify the timezone of log messages
999-
pub fn timezone(mut self, timezone: LogTimezone) -> Builder {
1000-
self.timezone = timezone;
1001-
self
1002-
}
1003-
1004942
/// Finish building ftlog logger
1005943
///
1006944
/// The call spawns a log thread to formatting log message into string,
1007945
/// and write to output target.
1008946
pub fn build(self) -> Result<Logger, IoError> {
1009-
let offset = match self.timezone {
1010-
LogTimezone::Local => Some(local_timezone()),
1011-
LogTimezone::Utc => None,
1012-
LogTimezone::Fixed(offset) => Some(offset),
1013-
};
1014-
let time_format = self.time_format.unwrap_or_else(|| {
1015-
time::format_description::parse_owned::<1>(
1016-
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]+[offset_hour]",
1017-
)
1018-
.unwrap()
1019-
});
1020947
let filters = self.filters;
1021948
// check appender name in filters are all valid
1022949
for appender_name in filters.iter().filter_map(|x| x.appender) {
@@ -1059,8 +986,6 @@ impl Builder {
1059986
root_level,
1060987
&mut missed_log,
1061988
&mut last_log,
1062-
offset,
1063-
&time_format,
1064989
);
1065990
}
1066991
Ok(LoggerInput::Flush) => {
@@ -1074,8 +999,6 @@ impl Builder {
1074999
root_level,
10751000
&mut missed_log,
10761001
&mut last_log,
1077-
offset,
1078-
&time_format,
10791002
)
10801003
} else {
10811004
break 'queue;

0 commit comments

Comments
 (0)