rs / zerolog

Zero Allocation JSON Logger
MIT License
10.39k stars 566 forks source link

[question] How to access `with` fields inside a hook #493

Open vijayrajah opened 1 year ago

vijayrajah commented 1 year ago

I'm using a hook to write the logs to graylog using GELF client ( "gopkg.in/Graylog2/go-gelf.v2/gelf")

it appears that there is no way to access with fields

like

log.With().Str("k","v).Logger().Info().Msg("some message")

I want to add the k as extra field (with its value as v) in GELF message.

is there a way we can do this?

cruzanstx commented 1 year ago

I ran into the same issue. I'm not sure if this is the most performant way to access it and it would be nice if it were built into the event object. I used reflection to access a readonly copy of the buf variable.

func (h Hook) Run(e *zerolog.Event, level zerolog.Level, msg string){
   logData := make(map[string]interface{})
   // create a string that appends } to the end of the buf variable you access via reflection
   ev := fmt.Sprintf("%s}", reflect.ValueOf(e).Elem().FieldByName("buf"))
   json.Unmarshal([]byte(ev), &logData)

   // now you can either access a map of the data (logData) or string of the data (ev)
}

I think the Event object should have a func that returns the string or a map of the buf variable like

func (e *zerolog.Event) GetEventString (string) {
   // if buffer only has { or is blank, could also do more checks to give a good default
   if len(reflect.ValueOf(e).Elem().FieldByName("buf")) < 2 {
      return "{ }"
   }
   ev := fmt.Sprintf("%s}", reflect.ValueOf(e).Elem().FieldByName("buf"))
   return ev
}