Bladeren bron

Merge pull request #79 from ctaoist/main

Customizable timestamps format
Sam Clements 2 jaren geleden
bovenliggende
commit
c32992bd7e
3 gewijzigde bestanden met toevoegingen van 51 en 4 verwijderingen
  1. 1 1
      README.md
  2. 12 0
      examples/timestamps_format.rs
  3. 38 3
      src/lib.rs

+ 1 - 1
README.md

@@ -2,7 +2,7 @@
 
 A logger that prints all messages with a readable output format.
 
-The output format is based on the format used by [Supervisord](https://github.com/Supervisor/supervisor), with timestamps in [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339) format.
+The output format is based on the format used by [Supervisord](https://github.com/Supervisor/supervisor), with timestamps in default [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339) format and custom format.
 
 * [Source on GitHub](https://github.com/borntyping/rust-simple_logger)
 * [Packages on Crates.io](https://crates.io/crates/simple_logger)

+ 12 - 0
examples/timestamps_format.rs

@@ -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.");
+}

+ 38 - 3
src/lib.rs

@@ -81,6 +81,8 @@ pub struct SimpleLogger {
     /// This field is only available if the `timestamps` feature is enabled.
     #[cfg(feature = "timestamps")]
     timestamps: Timestamps,
+    #[cfg(feature = "timestamps")]
+    timeformat: &'static [FormatItem<'static>],
 
     /// Whether to use color output or not.
     ///
@@ -111,6 +113,8 @@ impl SimpleLogger {
 
             #[cfg(feature = "timestamps")]
             timestamps: Timestamps::Utc,
+            #[cfg(feature = "timestamps")]
+            timeformat: time::macros::format_description!(""),
 
             #[cfg(feature = "colored")]
             colors: true,
@@ -265,6 +269,26 @@ impl SimpleLogger {
         self
     }
 
+    /// Custom timestamps format
+    ///
+    /// The syntax for the format_description macro can be found in the
+    /// [`time` crate book](https://time-rs.github.io/book/api/format-description.html).
+    ///
+    /// ```
+    /// simple_logger::SimpleLogger::new()
+    ///  .with_level(log::LevelFilter::Debug)
+    ///  .env()
+    ///  .with_custom_timestamps(time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))
+    ///  .init()
+    ///  .unwrap();
+    /// ```
+    #[must_use = "You must call init() to begin logging"]
+    #[cfg(feature = "timestamps")]
+    pub fn with_custom_timestamps(mut self, timeformat: &'static [FormatItem<'static>]) -> SimpleLogger {
+        self.timeformat = timeformat;
+        self
+    }
+
     /// Don't display any timestamps.
     ///
     /// This method is only available if the `timestamps` feature is enabled.
@@ -321,6 +345,17 @@ impl SimpleLogger {
         #[cfg(all(windows, feature = "colored"))]
         set_up_color_terminal();
 
+        // Set default timestamp format
+        #[cfg(feature = "timestamps")]
+        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.
          */
@@ -426,15 +461,15 @@ impl Log for SimpleLogger {
                                 "behaviour. See the time crate's documentation for more information. ",
                                 "(https://time-rs.github.io/internal-api/time/index.html#feature-flags)"
                             ))
-                            .format(&TIMESTAMP_FORMAT_OFFSET)
+                            .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()
                             .to_offset(offset)
-                            .format(&TIMESTAMP_FORMAT_OFFSET)
+                            .format(&self.timeformat)
                             .unwrap()
                     ),
                 }