-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_logger_test.go
48 lines (41 loc) · 958 Bytes
/
example_logger_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package gctx_test
import (
"context"
"fmt"
"sync"
"github.com/ansiwen/gctx"
)
type requestID struct{}
// "global" logger instance
func log(s string) {
ctx := gctx.Get()
reqID, _ := ctx.Value(requestID{}).(int)
fmt.Printf("[LOG] reqID: %d - %s\n", reqID, s)
}
// placeholder for an external library function without context support
// doing something and using a global logger
func someLibraryFunction() {
/* ... */
log("did something")
/* ... */
}
func Example_logger() {
var wg sync.WaitGroup
// asynchronously call a library function for 5 times
for i := 0; i < 5; i++ {
wg.Add(1)
ctx := context.WithValue(context.Background(), requestID{}, i)
go func() {
gctx.Set(ctx)
someLibraryFunction()
wg.Done()
}()
}
wg.Wait()
// Unordered output:
// [LOG] reqID: 0 - did something
// [LOG] reqID: 1 - did something
// [LOG] reqID: 2 - did something
// [LOG] reqID: 3 - did something
// [LOG] reqID: 4 - did something
}