Skip to content

Instantly share code, notes, and snippets.

@Thesmader
Last active January 24, 2024 04:59
Show Gist options
  • Save Thesmader/d4c53326953460996ec49c3f5cdfad07 to your computer and use it in GitHub Desktop.
Save Thesmader/d4c53326953460996ec49c3f5cdfad07 to your computer and use it in GitHub Desktop.
Slog handler for building a map representation of the JSON outputted by slog.JSONHandler
package maphandler
import (
"context"
"encoding/json"
"fmt"
"log/slog"
)
type group struct {
name string
attrs []slog.Attr
group *group
}
func (g *group) resolve() map[string]interface{} {
m := make(map[string]interface{})
if g.group == nil {
for _, attr := range g.attrs {
m[attr.Key] = attr.Value.Resolve().Any()
}
return m
}
m[g.group.name] = g.group.resolve()
for _, attr := range g.attrs {
m[attr.Key] = attr.Value.Resolve().Any()
}
return m
}
type MapHandler struct {
attrs []slog.Attr
group *group
}
func (h *MapHandler) Enabled(_ context.Context, _ slog.Level) bool {
return true
}
func (h *MapHandler) Handle(_ context.Context, r slog.Record) error {
m := make(map[string]interface{})
m["message"] = r.Message
for _, attr := range h.attrs {
m[attr.Key] = attr.Value.Resolve().Any()
}
if h.group != nil {
m[h.group.name] = h.group.resolve()
}
b, err := json.MarshalIndent(m, "", " ")
if err == nil {
fmt.Println(string(b))
}
return nil
}
func (h *MapHandler) WithGroup(name string) slog.Handler {
h2 := *h
copy(h2.attrs, h.attrs)
if h.group != nil {
h2.group = &group{name: h.group.name, attrs: h.group.attrs, group: &group{name: name}}
} else {
h2.group = &group{name: name}
}
return &h2
}
func (h *MapHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
h2 := *h
copy(h2.attrs, h.attrs)
if h.group != nil {
if h.group.group != nil {
h2.group = &group{attrs: h.group.attrs, name: h.group.name, group: &group{attrs: attrs, name: h.group.group.name}}
} else {
h2.group = &group{attrs: attrs, name: h.group.name}
}
} else {
h2.attrs = append(h2.attrs, attrs...)
}
return &h2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment