package xcontext import ( "context" "log/slog" ) type ctxLogKey struct{} type ctxLogAttrStore struct { attrs []slog.Attr } func WithLogFields(ctx context.Context, fields ...slog.Attr) context.Context { store, _ := ctx.Value(ctxLogKey{}).(ctxLogAttrStore) store.attrs = append(store.attrs, fields...) return context.WithValue(ctx, ctxLogKey{}, store) } func LogDebug(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) { log.LogAttrs(ctx, slog.LevelDebug, msg, append(attrs, getLogFields(ctx)...)...) } func LogInfo(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) { log.LogAttrs(ctx, slog.LevelInfo, msg, append(attrs, getLogFields(ctx)...)...) } func LogWarn(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) { log.LogAttrs(ctx, slog.LevelWarn, msg, append(attrs, getLogFields(ctx)...)...) } func LogError(ctx context.Context, log *slog.Logger, msg string, attrs ...slog.Attr) { log.LogAttrs(ctx, slog.LevelError, msg, append(attrs, getLogFields(ctx)...)...) } func LogWithError(ctx context.Context, log *slog.Logger, err error, msg string, attrs ...slog.Attr) { LogError(ctx, log, msg, append(attrs, slog.Any("err", err))...) } func getLogFields(ctx context.Context) []slog.Attr { store, _ := ctx.Value(ctxLogKey{}).(ctxLogAttrStore) return store.attrs }