-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlogger.go
100 lines (81 loc) · 1.95 KB
/
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package gogo
import (
"context"
"log"
"net/http"
"path"
"sync"
"github.com/dolab/logger"
)
// AppLogger defines log component of gogo, it implements Logger interface
// with pool support
type AppLogger struct {
*logger.Logger
mux sync.RWMutex
pool sync.Pool
requestID string
}
// NewAppLogger returns *AppLogger inited with args
func NewAppLogger(output, filename string) *AppLogger {
switch output {
case "stdout", "stderr", "null", "nil":
// skip
default:
if output[0] != '/' {
output = path.Join(output, filename+".log")
}
}
lg, err := logger.New(output)
if err != nil {
log.Panicf("logger.New(%s): %v\n", output, err)
}
alog := &AppLogger{
Logger: lg.New(),
}
// overwrite poo.New
alog.pool.New = func() interface{} {
return &AppLogger{
Logger: lg.New(),
}
}
return alog
}
// NewRequestLogger returns a Logger related with *http.Request.
//
// NOTE: It returns a dummy *AppLogger when no available Logger for the request.
func NewRequestLogger(r *http.Request) Logger {
return NewContextLogger(r.Context())
}
// NewContextLogger returns a Logger related with ctxLoggerKey.
func NewContextLogger(ctx context.Context) Logger {
alog, ok := ctx.Value(ctxLoggerKey).(Logger)
if !ok {
alog = NewAppLogger("stderr", "")
}
return alog
}
// New returns a new Logger with provided requestID which shared writer with current logger
func (alog *AppLogger) New(requestID string) Logger {
// shortcut
alog.mux.RLock()
if alog.requestID == requestID {
alog.mux.RUnlock()
return alog
}
defer alog.mux.RUnlock()
lg := alog.pool.Get()
if nlog, ok := lg.(*AppLogger); ok {
nlog.requestID = requestID
nlog.SetTags(requestID)
return nlog
}
return lg.(Logger).New(requestID)
}
// RequestID returns request id binded to the logger
func (alog *AppLogger) RequestID() string {
return alog.requestID
}
// Reuse puts the Logger back to pool for later usage
func (alog *AppLogger) Reuse(lg Logger) {
alog.pool.Put(lg)
}