Skip to content

Commit

Permalink
1. added examples/timestamps_format.rs
Browse files Browse the repository at this point in the history
2. could customize format for utc timestamps
  • Loading branch information
ctaoist committed Mar 15, 2023
1 parent c7ab668 commit 5998a66
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
12 changes: 12 additions & 0 deletions examples/timestamps_format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use simple_logger::SimpleLogger;
use time::macros::format_description;

fn main() {
SimpleLogger::new()
.env()
.with_custom_timestamps(format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))
.init()
.unwrap();

log::warn!("This is an example message with custom timestamp format.");
}
14 changes: 12 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl SimpleLogger {
#[cfg(feature = "timestamps")]
timestamps: Timestamps::Utc,
#[cfg(feature = "timestamps")]
timeformat: TIMESTAMP_FORMAT_OFFSET,
timeformat: time::macros::format_description!(""),

#[cfg(feature = "colored")]
colors: true,
Expand Down Expand Up @@ -345,6 +345,16 @@ impl SimpleLogger {
#[cfg(all(windows, feature = "colored"))]
set_up_color_terminal();

// Set default timestamp format
if self.timeformat.len() <= 0 {
self.timeformat = match self.timestamps {
Timestamps::Local => TIMESTAMP_FORMAT_OFFSET,
Timestamps::Utc => TIMESTAMP_FORMAT_UTC,
Timestamps::UtcOffset(_) => TIMESTAMP_FORMAT_OFFSET,
_ => self.timeformat,
};
}

/* Sort all module levels from most specific to least specific. The length of the module
* name is used instead of its actual depth to avoid module name parsing.
*/
Expand Down Expand Up @@ -453,7 +463,7 @@ impl Log for SimpleLogger {
.format(&self.timeformat)
.unwrap()
),
Timestamps::Utc => format!("{} ", OffsetDateTime::now_utc().format(&TIMESTAMP_FORMAT_UTC).unwrap()),
Timestamps::Utc => format!("{} ", OffsetDateTime::now_utc().format(&self.timeformat).unwrap()),
Timestamps::UtcOffset(offset) => format!(
"{} ",
OffsetDateTime::now_utc()
Expand Down

0 comments on commit 5998a66

Please sign in to comment.