Skip to content

Commit 5998a66

Browse files
committed
1. added examples/timestamps_format.rs
2. could customize format for utc timestamps
1 parent c7ab668 commit 5998a66

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

examples/timestamps_format.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
use simple_logger::SimpleLogger;
2+
use time::macros::format_description;
3+
4+
fn main() {
5+
SimpleLogger::new()
6+
.env()
7+
.with_custom_timestamps(format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))
8+
.init()
9+
.unwrap();
10+
11+
log::warn!("This is an example message with custom timestamp format.");
12+
}

src/lib.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ impl SimpleLogger {
114114
#[cfg(feature = "timestamps")]
115115
timestamps: Timestamps::Utc,
116116
#[cfg(feature = "timestamps")]
117-
timeformat: TIMESTAMP_FORMAT_OFFSET,
117+
timeformat: time::macros::format_description!(""),
118118

119119
#[cfg(feature = "colored")]
120120
colors: true,
@@ -345,6 +345,16 @@ impl SimpleLogger {
345345
#[cfg(all(windows, feature = "colored"))]
346346
set_up_color_terminal();
347347

348+
// Set default timestamp format
349+
if self.timeformat.len() <= 0 {
350+
self.timeformat = match self.timestamps {
351+
Timestamps::Local => TIMESTAMP_FORMAT_OFFSET,
352+
Timestamps::Utc => TIMESTAMP_FORMAT_UTC,
353+
Timestamps::UtcOffset(_) => TIMESTAMP_FORMAT_OFFSET,
354+
_ => self.timeformat,
355+
};
356+
}
357+
348358
/* Sort all module levels from most specific to least specific. The length of the module
349359
* name is used instead of its actual depth to avoid module name parsing.
350360
*/
@@ -453,7 +463,7 @@ impl Log for SimpleLogger {
453463
.format(&self.timeformat)
454464
.unwrap()
455465
),
456-
Timestamps::Utc => format!("{} ", OffsetDateTime::now_utc().format(&TIMESTAMP_FORMAT_UTC).unwrap()),
466+
Timestamps::Utc => format!("{} ", OffsetDateTime::now_utc().format(&self.timeformat).unwrap()),
457467
Timestamps::UtcOffset(offset) => format!(
458468
"{} ",
459469
OffsetDateTime::now_utc()

0 commit comments

Comments
 (0)