-
Notifications
You must be signed in to change notification settings - Fork 8
/
trace.go
52 lines (43 loc) · 1.04 KB
/
trace.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
49
50
51
52
package logs
import (
"context"
"unsafe"
)
// go clean -testcache // Delete all cached test results
const (
traceStr = "23456789abcdefghijkmnpqrstuvwxyz" //32
traceMask = 1<<5 - 1 //11111
traceSize = 8 //6-12
)
func trace() string {
buf := make([]byte, traceSize)
for idx, cache := 0, fastRand(); idx < traceSize; {
buf[idx] = traceStr[cache&traceMask]
cache >>= 5
idx++
}
return unsafe.String(&buf[0], len(buf))
}
func TraceId() string {
return trace()
}
func TraceOf(ctx context.Context) string {
traceId, _ := ctx.Value(traceKey).(string)
return traceId
}
//go:linkname fastRand runtime.fastrand64
func fastRand() uint64
const traceKey = "zlogs-trace-key"
func TraceCtx(ctx context.Context, tarceid ...string) context.Context {
val := ctx.Value(traceKey)
if val == nil {
var id = ""
if len(tarceid) == 0 {
id = trace()
} else {
id = tarceid[0]
}
ctx = context.WithValue(ctx, traceKey, id)
}
return ctx
}