41 lines
1.1 KiB
Go
41 lines
1.1 KiB
Go
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 getLogFields(ctx context.Context) []slog.Attr {
|
|
store, _ := ctx.Value(ctxLogKey{}).(ctxLogAttrStore)
|
|
return store.attrs
|
|
}
|