This repository has been archived by the owner on Jun 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
264 lines (210 loc) · 7.31 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package rec
import (
"fmt"
"io"
"os"
"sync"
"time"
)
var defaultLogger = Must(NewWithConfig(os.Stderr, NewConfig())) // nolint: gochecknoglobals
// Logger is the main struct of rec.
type Logger struct {
mu sync.Mutex
customSeverities map[Severity]*severityStrings
config *Config
contextFields []byte
writer io.Writer
}
// Lock locks mu. If the lock is already in use, the calling goroutine blocks until the mutex is available.
func (l *Logger) Lock() {
l.mu.Lock()
}
// Unlock unlocks mu. It is a run-time error if m is not locked on entry to Unlock.
// A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it.
func (l *Logger) Unlock() {
l.mu.Unlock()
}
// NewWithConfig creates a *rec.Logger from *rec.Config.
func NewWithConfig(writer io.Writer, config *Config) (*Logger, error) {
if err := config.validate(); err != nil {
return nil, fmt.Errorf("*Config.validate: %w", err)
}
return &Logger{
mu: sync.Mutex{},
customSeverities: defaultSeverities(),
config: config,
contextFields: make([]byte, 0),
writer: writer,
}, nil
}
// New creates a *rec.Logger from rec.Option.
func New(writer io.Writer, options ...Option) (*Logger, error) {
config := NewConfig()
for _, opt := range options {
if err := opt.f(config); err != nil {
return nil, fmt.Errorf("%s: %w", opt.name, err)
}
}
return NewWithConfig(writer, config)
}
// Must is used as Must(rec.New()) or Must(rec.NewWithConfig()).
// If the passed function returns an error, Must() will panic.
func Must(l *Logger, err error) *Logger {
if err != nil {
panic(fmt.Errorf("Must: %w", err))
}
return l
}
// L returns default `*rec.Logger` in rec package.
func L() *Logger {
return defaultLogger
}
// ReplaceDefaultLogger replaces the default logger in rec package.
// and returns a function for rollback logger.
func ReplaceDefaultLogger(l *Logger) (rollback func()) {
backupDefaultLogger := defaultLogger
defaultLogger = l
return func() {
defaultLogger = backupDefaultLogger
}
}
// Copy returns copied `*rec.Logger`.
func (l *Logger) Copy() *Logger {
copiedLogger := Must(NewWithConfig(l.writer, NewConfig()))
// subst copied customSeverities
for severity, severityStrings := range l.customSeverities {
copiedSeverityStrings := *severityStrings // copy
copiedLogger.customSeverities[severity] = &copiedSeverityStrings
}
// subst copied LoggerOptions
copiedLoggerConfig := *l.config // copy
copiedLogger.config = &copiedLoggerConfig
// copy context fields
if len(l.contextFields) > 0 {
copiedLogger.contextFields = append(copiedLogger.contextFields, l.contextFields...)
}
return copiedLogger
}
// AddCallerSkip copied `*rec.Logger` that added caller skip.
func (l *Logger) AddCallerSkip(callerSkip int) *Logger {
copied := l.Copy()
copied.config.CallerSkip += callerSkip
return copied
}
// With returns a `rec.Logger` with fixed `rec.Fields` added.
//
// For example, for the following `rec.Logger`:
//
// l := rec.Must(rec.New(os.Stderr)).With(rec.String("field", "added"))
// l.InfoLog("rec")
//
// This will output a log like the following:
//
// $ go run main.go
// {"timestamp":"...",...,"message":"rec","field":"added"}
func (l *Logger) With(fields ...Field) *Logger {
copied := l.Copy()
for i := range fields {
copied.contextFields = append(appendJSONField(copied.contextFields, fields[i]), ',')
}
return copied
}
// Renew copies the `*rec.Logger`, applies `rec.Option` to it, and returns it.
func (l *Logger) Renew(options ...Option) (*Logger, error) {
copied := l.Copy()
for _, opt := range options {
if err := opt.f(copied.config); err != nil {
return nil, fmt.Errorf("%s: %w", opt.name, err)
}
}
return copied, nil
}
// RenewWriter copies the `*rec.Logger`, set a new io.Writer for it, and returns it.
func (l *Logger) RenewWriter(writer io.Writer) *Logger {
copied := l.Copy()
copied.writer = writer
return copied
}
// nolint: cyclop, funlen
func (l *Logger) write(now time.Time, severity Severity, message string, fields ...Field) {
if severity < l.config.SeverityThreshold {
return
}
b := bufferPool.Get().(*buffer) // nolint: forcetypeassert
defer bufferPool.Put(b)
// reset
b.Buffer = b.Buffer[:0]
// {
b.Buffer = append(b.Buffer, '{')
// {"timestamp":"...",
if l.config.UseTimestampField {
b.Buffer = append(b.Buffer, '"')
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.TimestampFieldKey)
b.Buffer = append(b.Buffer, `":`...)
b.Buffer = appendTimeFieldValue(b.Buffer, now, l.config.TimestampFieldFormat)
b.Buffer = append(b.Buffer, ',')
}
// {"timestamp":"...","severity":"...",
if l.config.UseSeverityField {
b.Buffer = append(b.Buffer, '"')
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.SeverityFieldKey)
b.Buffer = append(b.Buffer, `":"`...)
if l.config.UseUppercaseSeverity {
b.Buffer = appendJSONEscapedString(b.Buffer, l.uppercase(severity))
} else {
b.Buffer = appendJSONEscapedString(b.Buffer, l.lowercase(severity))
}
b.Buffer = append(b.Buffer, `",`...)
}
// {"timestamp":"...","severity":"...","hostname":"...",
if l.config.UseHostnameField {
b.Buffer = append(b.Buffer, '"')
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.HostnameFieldKey)
b.Buffer = append(b.Buffer, `":"`...)
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.HostnameFieldValue)
b.Buffer = append(b.Buffer, `",`...)
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...",
if l.config.UseCallerField {
b.Buffer = append(b.Buffer, '"')
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.CallerFieldKey)
b.Buffer = append(b.Buffer, `":"`...)
b.Buffer = appendCaller(b.Buffer, l.config.CallerSkip, l.config.UseShortCaller)
b.Buffer = append(b.Buffer, `",`...)
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...","message":"...",
if l.config.UseMessageField {
b.Buffer = append(b.Buffer, '"')
b.Buffer = appendJSONEscapedString(b.Buffer, l.config.MessageFieldKey)
b.Buffer = append(b.Buffer, `":"`...)
b.Buffer = appendJSONEscapedString(b.Buffer, message)
b.Buffer = append(b.Buffer, `",`...)
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...","message":"...","context":"...",
if len(l.contextFields) > 0 {
b.Buffer = append(b.Buffer, l.contextFields...)
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...","message":"...","context":"...","fields":"...",
for i := range fields {
b.Buffer = append(appendJSONField(b.Buffer, fields[i]), ',')
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...","message":"...","context":"...","fields":"..."}
if b.Buffer[len(b.Buffer)-1] == ',' {
b.Buffer[len(b.Buffer)-1] = '}'
} else {
b.Buffer = append(b.Buffer, '}')
}
// {"timestamp":"...","severity":"...","hostname":"...","caller":"...","message":"...","context":"...","fields":"..."}\n
b.Buffer = append(b.Buffer, l.config.LineSeparator...)
if _, err := l.writer.Write(b.Buffer); err != nil {
err = fmt.Errorf("(*rec.Logger).write: writer=%#v: Write: %w", l.writer, err)
defaultLogger.write(now, ERROR, err.Error(), Error(err))
}
}
func (l *Logger) Write(b []byte) (int, error) {
if len(b) > 0 && b[len(b)-1] == '\n' {
b = b[:len(b)-1]
}
l.write(time.Now(), l.config.DefaultSeverity, string(b))
return len(b), nil
}