slog-context icon indicating copy to clipboard operation
slog-context copied to clipboard

WithValue on contex with existing fields affects the parent context

Open deansg opened this issue 3 months ago • 0 comments

When calling WithValue on a ctx.Context that already has some attached fields, it will affect the parent context as well. For example:

package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/PumpkinSeed/slog-context"
)

func main() {
	slog.SetDefault(slog.New(slogcontext.NewHandler(slog.NewJSONHandler(os.Stdout, nil))))

	ctx := slogcontext.WithValue(context.Background(), "number", 12)
        ctx2 := slogcontext.WithValue(ctx, "stringField", "data")
	slog.InfoContext(ctx, "log1") // This will contain the stringField field even though it was meant to be added only to ctx2
	slog.InfoContext(ctx2, "log2")
}

deansg avatar May 21 '24 06:05 deansg