-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
41 lines (33 loc) · 836 Bytes
/
log.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
package webutil
import (
"context"
"fmt"
"log"
)
type contextLogger struct {
context.Context
l *log.Logger
}
type contextLoggerValue int
const contextLoggerLogger contextLoggerValue = 1
func NewContextLogger(ctx context.Context, l *log.Logger) context.Context {
return &contextLogger{ctx, l}
}
func (ctx *contextLogger) Value(key interface{}) interface{} {
if key == contextLoggerLogger {
return ctx.l
}
return ctx.Context.Value(key)
}
func CtxPrintf(ctx context.Context, format string, v ...interface{}) {
if l, ok := ctx.Value(contextLoggerLogger).(*log.Logger); ok {
l.Output(2, fmt.Sprintf(format, v...))
} else {
log.Output(2, fmt.Sprintf(format, v...))
}
}
func CtxSetPrefix(ctx context.Context, prefix string) {
if l, ok := ctx.Value(contextLoggerLogger).(*log.Logger); ok {
l.SetPrefix(prefix)
}
}