tokio-rs / tracing

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

add a trait like slog::KV #1288

Open Sherlock-Holo opened 3 years ago

Sherlock-Holo commented 3 years ago

Feature Request

Crates

tracing

Motivation

consider we have a request base info like

#[derive(Debug, Default, Clone)]
struct BaseRequest {
    request_id: String,
    retry_count: u8,
    user_id: String,
    user_name: String,
    is_vip: bool,
}

for now when we print log with messages in the BaseRequest, we have to use

info!(request_id = base_req.request_id, retry_count = base_req.retry_count, user_id = base_req.user_id, user_name = base_req.user_name, is_vip = base_req.is_vip, "message")

if we write many logs we have to write the xxx = yyy many times, it makes me so sad.

if tracing add a new trait like slog::KV, we can print log easily like info!(extra_key = extra_value, base_req, "message")

Proposal

add a new trait like slog::KV

trait KV {
  // Serializer is something that can allow user emit custom key and value
  fn serialize(&self, serializer: &mut Serializer) -> Result
}

the BaseRequest can implement this trait

impl KV for BaseRequest {
    fn serialize(&self, serializer: &mut dyn Serializer) -> Result {
        serializer.emit_str("request_id", &self.request_id)?;
        serializer.emit_u8("retry_count", self.retry_count)?;
        serializer.emit_str("user_id", &self.user_id)?;
        serializer.emit_str("user_name", &self.user_name)?;
        serializer.emit_bool("is_vip", self.is_vip)
    }
}

Alternatives

Folyd commented 3 years ago

I think you should use tracing::info!(?base_req) or tracing::info!(%base_req). See https://tracing.rs/tracing/index.html#recording-fields

Sherlock-Holo commented 3 years ago

@Folyd these ways only print the struct as string, not like slog::KV

davidbarsky commented 3 years ago

A quick note: there's some discussion in the Tokio Discord in the #valuable channel on rethinking the Value trait. At the moment, the discussion focused on requirements.