WithAttrs returns a context carrying slog attributes for context-aware log calls.
(ctx context.Context, attrs ...slog.Attr)
| 9 | |
| 10 | // WithAttrs returns a context carrying slog attributes for context-aware log calls. |
| 11 | func WithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context { |
| 12 | if len(attrs) == 0 { |
| 13 | return ctx |
| 14 | } |
| 15 | |
| 16 | existingAttrs := attrsFromContext(ctx) |
| 17 | replacedKeys := make(map[string]struct{}, len(attrs)) |
| 18 | for _, attr := range attrs { |
| 19 | replacedKeys[attr.Key] = struct{}{} |
| 20 | } |
| 21 | |
| 22 | mergedAttrs := make([]slog.Attr, 0, len(existingAttrs)+len(attrs)) |
| 23 | for _, attr := range existingAttrs { |
| 24 | if _, ok := replacedKeys[attr.Key]; ok { |
| 25 | continue |
| 26 | } |
| 27 | mergedAttrs = append(mergedAttrs, attr) |
| 28 | } |
| 29 | mergedAttrs = append(mergedAttrs, attrs...) |
| 30 | return context.WithValue(ctx, contextAttrsKey{}, mergedAttrs) |
| 31 | } |
| 32 | |
| 33 | func attrsFromContext(ctx context.Context) []slog.Attr { |
| 34 | if ctx == nil { |