Types like http.Request and slog.LogValuer

219 views
Skip to first unread message

Jens-Uwe Mager

unread,
Jul 27, 2023, 10:01:27 AM7/27/23
to golang-nuts
I am trying to convert some older code to slog and I am running into the issue that if some data structure contains http.Request I get the message:

{"time":"2023-07-27T15:49:04.744214+02:00","level":"DEBUG","msg":"req","r":"!ERROR:json: unsupported type: func() (io.ReadCloser, error)"}

So I believed it would be a good idea to add a LogValue() function to http.Request that used httputil.DumpRequest(), but that does not work as I cannot add methods from my code. Any good idea to approach that?

Jonathan Amsterdam

unread,
Jul 29, 2023, 6:18:53 AM7/29/23
to golang-nuts
I would write a type that wraps the request and implements LogValuer. Then you would log the request as

     logger.Debug("req", "r", requestWrapper{r})

Jens-Uwe Mager

unread,
Jul 29, 2023, 10:23:33 AM7/29/23
to golang-nuts
There is a slight problem here that the requestWrapper would have to be implemented very deep through many layers of library. For example there might be a data structure passed down a chain of handlers with a custom argument structure, which contains a http.Request per some old design decisions. Switching to slog probably makes me revisit this design, as I cannot easily get the http.Request out of that structure easily. And this custom structure is logged all over the place.

Oh well.

Jonathan Amsterdam

unread,
Jul 30, 2023, 3:07:48 PM7/30/23
to Jens-Uwe Mager, golang-nuts
Another idea: write a handler that wraps whatever handler you usually use. That handler looks through the Record for attr values of type *http.Request, and replaces them with whatever formatting you want.
You might even be able to do that with a ReplaceAttr function with the built-in handlers.

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/PYIIhY6pNM4/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a42d3bce-86d0-43dd-8895-4bd3a524cddfn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages