Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
vijayrajah opened this issue Oct 11, 2022 · 1 comment
Open

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

vijayrajah opened this issue Oct 11, 2022 · 1 comment

Comments

@vijayrajah
Copy link

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
Copy link

cruzanstx commented Mar 7, 2023

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants