File tree Expand file tree Collapse file tree 2 files changed +62
-2
lines changed Expand file tree Collapse file tree 2 files changed +62
-2
lines changed Original file line number Diff line number Diff line change @@ -4,9 +4,12 @@ import (
4
4
"context"
5
5
)
6
6
7
+ type FieldsType map [string ]string
8
+
7
9
type (
8
- ctxLevelKey struct {}
9
- ctxNamesKey struct {}
10
+ ctxLevelKey struct {}
11
+ ctxNamesKey struct {}
12
+ ctxFieldsKey struct {}
10
13
)
11
14
12
15
func WithLevel (ctx context.Context , lvl Level ) context.Context {
@@ -36,6 +39,29 @@ func NamesFromContext(ctx context.Context) []string {
36
39
return v [:len (v ):len (v )] // prevent re
37
40
}
38
41
42
+ func WithFields (ctx context.Context , fields FieldsType ) context.Context {
43
+ existing := FieldsFromContext (ctx )
44
+ merged := make (FieldsType , len (existing )+ len (fields ))
45
+
46
+ for k , v := range existing {
47
+ merged [k ] = v
48
+ }
49
+
50
+ for k , v := range fields {
51
+ merged [k ] = v
52
+ }
53
+
54
+ return context .WithValue (ctx , ctxFieldsKey {}, merged )
55
+ }
56
+
57
+ func FieldsFromContext (ctx context.Context ) FieldsType {
58
+ if fields , _ := ctx .Value (ctxFieldsKey {}).(FieldsType ); fields != nil {
59
+ return fields
60
+ }
61
+
62
+ return FieldsType {}
63
+ }
64
+
39
65
func with (ctx context.Context , lvl Level , names ... string ) context.Context {
40
66
return WithLevel (WithNames (ctx , names ... ), lvl )
41
67
}
Original file line number Diff line number Diff line change @@ -90,3 +90,37 @@ func TestWithNamesRaceRegression(t *testing.T) {
90
90
}
91
91
})
92
92
}
93
+
94
+ func TestFieldsFromContext (t * testing.T ) {
95
+ for _ , tt := range []struct {
96
+ ctx context.Context
97
+ fields FieldsType
98
+ }{
99
+ {
100
+ ctx : context .Background (),
101
+ fields : FieldsType {},
102
+ },
103
+ {
104
+ ctx : WithFields (context .Background (), FieldsType {"a" : "1" , "b" : "1" }),
105
+ fields : FieldsType {"a" : "1" , "b" : "1" },
106
+ },
107
+ {
108
+ ctx : WithFields (
109
+ WithFields (context .Background (), FieldsType {"a" : "1" , "b" : "1" }),
110
+ FieldsType {"a" : "2" , "b" : "2" },
111
+ ),
112
+ fields : FieldsType {"a" : "2" , "b" : "2" },
113
+ },
114
+ {
115
+ ctx : WithFields (
116
+ WithFields (context .Background (), FieldsType {"a" : "1" , "b" : "1" }),
117
+ FieldsType {"a" : "3" },
118
+ ),
119
+ fields : FieldsType {"a" : "3" , "b" : "1" },
120
+ },
121
+ } {
122
+ t .Run ("" , func (t * testing.T ) {
123
+ require .Equal (t , tt .fields , FieldsFromContext (tt .ctx ))
124
+ })
125
+ }
126
+ }
You can’t perform that action at this time.
0 commit comments