A logging implementation for the log crate that logs structured values as JSON (CBOR, or any other) into a file, stderr, stdout, or any other.
See the [API documentation] for more.
```rust use serde::Serialize; use std::{io, time::SystemTime, time::UNIXEPOCH}; use structuredlogger::{newjsonwriter, Logger};
fn main() { // Initialize the logger. Logger::new() // set a specific writer (format to JSON, write to stdout) for target "request". .withtargetwriter("request", newjsonwriter(io::stdout())) .init();
let kv = ContextLog {
uid: "user123".to_string(),
action: "upate_book".to_string(),
};
log::info!("hello world");
// {"target":"simple","message":"hello world","level":"INFO"}
// mock request data
log::info!(target: "request",
method = "GET",
path = "/hello",
status = 200 as u16,
start = unix_ms(),
elapsed = 10 as u64,
kv = log::as_serde!(kv);
"",
);
// {"method":"GET","target":"request","message":"","path":"/hello","status":200,"level":"INFO","start":1679647263247,"kv":{"uid":"user123","action":"upate_book"},"elapsed":10}
}
struct ContextLog { uid: String, action: String, }
fn unixms() -> u64 { let ts = SystemTime::now() .durationsince(UNIXEPOCH) .expect("system time before Unix epoch"); ts.asmillis() as u64 } ```