custom slog Handler which adds Attribute and WithGroup

499 views
Skip to first unread message

Johann Höchtl

unread,
Oct 5, 2023, 11:59:30 AM10/5/23
to golang-nuts
I created a custom slog Handler which adds an attribute eventId which is a GUID

A NewLogger function returns that logger wrapped into a group: Every further key-value provided should go into that group.

Unfortunately the eventId also gets promoted into that group although it should be at the parent level.


Thank you for your help, Johann

Johann Höchtl

unread,
Oct 23, 2023, 9:50:46 AM10/23/23
to golang-nuts
As I got zero reply to that answer, let me rephrase it probably more easily:

I would like to use slog, no other logging library
I would like to have an entry called eventID which is at the root level and has a unique uuid for every log entry
I would like to use a group for every application specific key-val pairs

What I trired so far:
  • Use a Handler to add eventID : The key gets added to the logger yet at the group nesting level, not at the root level
  • Use a ReplaceAttr-Function: I add the key on initiailisation yet leave the value unassigned to Replace it in the ReplaceAttr-Function: The ReplaceAttr-Function sees the  root level addded eventID only untill a call to .WithGroup, then the  eventId is no longer available within the ReplaceAttr-Function

Any help?

Sean Liao

unread,
Oct 23, 2023, 1:53:55 PM10/23/23
to golang-nuts
The slog API doesn't allow wrapping handlers this way. slog.Handlers hold state for the current open group.
You'll need a full implementation of a handler to do this.

(Technically it's possible if you record the group/attrs in With/WithGroup yourself and only call the wrapped handler in Handle, but you lose any preformatting performance benefits a handler may have implemented.)

- sean


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/16dc9f51-6c8c-4fd9-9942-5e365399e26dn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages