/
logger.go
45 lines (37 loc) · 943 Bytes
/
logger.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
package logging
import (
"context"
"crypto/rand"
"encoding/hex"
"go.uber.org/zap"
)
type contextKey string
const loggerKey = contextKey("logger")
func L(ctx context.Context) *zap.Logger {
if ctx != nil {
if l, ok := ctx.Value(loggerKey).(*zap.Logger); ok {
return l
}
}
return zap.L()
}
// func ForRequest(
// ctx context.Context,
// timeout time.Duration,
// ) (context.Context, context.CancelFunc, *zap.Logger) {
// lg := L(ctx).With(zap.String("req_id", requestID()))
// ctx = context.WithValue(ctx, loggerKey, lg)
// ctx, done := context.WithTimeout(ctx, timeout)
// return ctx, done, lg
// }
func ForRequest(ctx context.Context) (context.Context, *zap.Logger) {
lg := L(ctx).With(zap.String("req_id", requestID()))
return context.WithValue(ctx, loggerKey, lg), lg
}
func requestID() string {
var buf [8]byte
if _, err := rand.Read(buf[:]); err != nil {
panic(err)
}
return hex.EncodeToString(buf[:])
}