tokio-rs / tracing

Application level tracing for Rust.
https://tracing.rs
MIT License
5.36k stars 699 forks source link

Retrieve timestamp from `FormatTime` as string #2338

Open pigeonhands opened 1 year ago

pigeonhands commented 1 year ago

Feature Request

Crates

tracing-subscriber

Motivation

I'm trying to create a custom json fmt::FormatEvent and need to get a timestamp string to serialize into the json. Using the Json formatter as reference within the library, it uses Writer::new, witch is not usable externally.

Proposal

Either 1) Make Writer::new public (as suggested #2223) 2) Change the signature of FormatTime::format_time to use io::Write 2) Add a get_timestamp_string method to FormatTime

pub trait FormatTime {
   ...
    fn get_timestamp_string(&self) -> result::Result<String, Error> {
        let mut timestamp = String::new();
        self.timer.format_time(&mut Writer::new(&mut timestamp))?;
        Ok(timestamp)
    }
}

I'm happy to create a PR for this with whatever solution is the best fit for this project.

pigeonhands commented 1 year ago

I think that making Writer::new is the best solution as it would allow re-using FormatEvent's in custom Layers too (it seems to be necessary for this)