-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
48 lines (37 loc) · 857 Bytes
/
ctx.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 log
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
type ctxLoggerMarker struct{}
var (
ctxLoggerKey = &ctxLoggerMarker{}
NullLogger = NewLogger(Options{}, ioutil.Discard)
DefaultLogger = NewLogger(Options{Level: "error"}, os.Stdout)
debugOutput io.Writer
)
func SetDebugOutput(w io.Writer) {
debugOutput = w
}
func Extract(ctx context.Context) *Entry {
l, ok := ctx.Value(ctxLoggerKey).(*Entry)
if !ok {
return NewEntry(DefaultLogger)
}
return l
}
func ToContext(ctx context.Context, logger *Entry) context.Context {
return context.WithValue(ctx, ctxLoggerKey, logger)
}
func Debugf(s string, args ...interface{}) {
if debugOutput == nil {
debugOutput = os.Stdout
}
logPrefix := "[" + time.Now().Format("2006/01/02 15:04:05") + "] "
suffix := "\n"
fmt.Fprintf(debugOutput, logPrefix+s+suffix, args...)
}