Standard library / log/slog

slog.LogAttrs()

Log at an explicit severity with typed Attr values. Expected stdout: '{"level":"INFO","msg":"ready","count":2}\n'.

Formal Syntax & Structure

go syntaxgo
func LogAttrs(ctx context.Context, level Level, msg string, attrs ...Attr)

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext passed to the handler.
levelLevelSeverity of the event or minimum level.
msgstringHuman-readable log message.
attrs...AttrStructured attributes.

Working Example

Example Snippetgo
package main
import (  "bytes"  "context"  "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)  slog.SetDefault(l)  slog.LogAttrs(context.Background(), slog.LevelInfo, "ready", slog.Int("count", 2))  fmt.Print(b.String())}
Go Reference