Standard library / log/slog

slog.JSONHandler.WithAttrs()

Return a handler with additional persistent attributes. Expected stdout: '{"level":"INFO","msg":"ready","n":2}\n'.

Formal Syntax & Structure

go syntaxgo
func (h *JSONHandler) WithAttrs(attrs []Attr) Handler

Parameters & Attributes

NameTypeDescription
attrs[]AttrStructured attributes.

Return Value

Handler

Return a handler with additional persistent attributes.

Working Example

Example Snippetgo
package main
import (  "bytes"  "context"  "fmt"  "log/slog"  "time")
func check(e error) {  if e != nil {    panic(e)  }}
func main() {  var b bytes.Buffer  h := slog.NewJSONHandler(&b, nil)  child := h.WithAttrs([]slog.Attr{slog.Int("n", 2)})  check(child.Handle(context.Background(), slog.NewRecord(time.Time{}, slog.LevelInfo, "ready", 0)))  fmt.Print(b.String())}
Go Reference