Standard library / log/slog

slog.DebugContext()

Log a DEBUG event with optional attributes if enabled by the handler. Pass the context to the handler. Expected stdout: '{"level":"DEBUG","msg":"ready","count":2}\n'.

Formal Syntax & Structure

go syntaxgo
func DebugContext(ctx context.Context, msg string, args ...any)

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext passed to the handler.
msgstringHuman-readable log message.
args...anyAlternating key/value pairs or Attr values.

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.DebugContext(context.Background(), "ready", "count", 2)  fmt.Print(b.String())}
Go Reference