Standard library / log/slog
slog.Logger.WithGroup()
Create a logger whose subsequent attributes are grouped under the named key. Expected stdout: '{"level":"INFO","msg":"ready","request":{"id":2}}\n'.
Formal Syntax & Structure
go syntaxgo
func (l *Logger) WithGroup(name string) *LoggerParameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | Group name. |
Return Value
*Logger
Create a logger whose subsequent attributes are grouped under the named key.
Working Example
Example Snippetgo
package main
import ( "bytes" "fmt" "log/slog")
func logger(b *bytes.Buffer) *slog.Logger { return slog.New(slog.NewJSONHandler(b, &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if len(groups) == 0 && a.Key == slog.TimeKey { return slog.Attr{} } return a }}))}
func main() { var b bytes.Buffer l := logger(&b) l.WithGroup("request").Info("ready", "id", 2) fmt.Print(b.String())}