Skip to content

Commit

Permalink
Add feature for readable timestamp string
Browse files Browse the repository at this point in the history
  • Loading branch information
雷青 committed Aug 23, 2021
1 parent 94e5aa8 commit 2f3a219
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ keywords = ["pretty-printer", "ndjson", "femme", "log", "logger"]
readme = "README.md"
edition = "2018"

[features]
readable_timestamp = ["chrono"]

[dependencies]
log = { version = "0.4.7", features = ["kv_unstable", "std"] }
serde = "1.0.97"
serde_derive = "1.0.97"
serde_json = "1.0.56"
cfg-if = "0.1.9"
chrono = { version = "0.4.19", optional = true }

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3.25", features = ["console"] }
Expand Down
24 changes: 22 additions & 2 deletions src/ndjson.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Print logs as ndjson.
#[cfg(readable_timestamp)]
use chrono::prelude::*;
use log::{kv, LevelFilter, Log, Metadata, Record};
use std::io::{self, StdoutLock, Write};
use std::time;
Expand All @@ -24,8 +26,26 @@ impl Log for Logger {
let stdout = io::stdout();
let mut handle = stdout.lock();
let level = get_level(record.level());
let time = time::UNIX_EPOCH.elapsed().unwrap().as_millis();
write!(&mut handle, "{{\"level\":{},\"time\":{},\"msg\":", level, time).unwrap();
#[cfg(not(readable_timestamp))]
{
let time = time::UNIX_EPOCH.elapsed().unwrap().as_millis();
write!(
&mut handle,
"{{\"level\":{},\"time\":{},\"msg\":",
level, time
)
.unwrap();
}
#[cfg(readable_timestamp)]
{
let time = Local::now().format("%Y-%m-%d %H:%M:%S%.f%z");
write!(
&mut handle,
"{{\"level\":{},\"time\":\"{}\",\"msg\":",
level, time
)
.unwrap();
}
serde_json::to_writer(&mut handle, record.args()).unwrap();
format_kv_pairs(&mut handle, &record);
writeln!(&mut handle, "}}").unwrap();
Expand Down

0 comments on commit 2f3a219

Please sign in to comment.