/
log.go
363 lines (311 loc) · 10.9 KB
/
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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vlog
import (
"errors"
"fmt"
"os"
"runtime"
"sync"
"v.io/x/lib/llog"
)
const (
initialMaxStackBufSize = 128 * 1024
)
// Level specifies a level of verbosity for V logs.
// It can be set via the Level optional parameter to Configure.
// It implements the flag.Value interface to support command line option parsing.
type Level llog.Level
// Set is part of the flag.Value interface.
func (l *Level) Set(v string) error {
return (*llog.Level)(l).Set(v)
}
// Get is part of the flag.Value interface.
func (l *Level) Get(v string) interface{} {
return *l
}
// String is part of the flag.Value interface.
func (l *Level) String() string {
return (*llog.Level)(l).String()
}
// StderrThreshold identifies the sort of log: info, warning etc.
// The values match the corresponding constants in C++ - e.g WARNING etc.
// It can be set via the StderrThreshold optional parameter to Configure.
// It implements the flag.Value interface to support command line option parsing.
type StderrThreshold llog.Severity
// Set is part of the flag.Value interface.
func (s *StderrThreshold) Set(v string) error {
return (*llog.Severity)(s).Set(v)
}
// Get is part of the flag.Value interface.
func (s *StderrThreshold) Get(v string) interface{} {
return *s
}
// String is part of the flag.Value interface.
func (s *StderrThreshold) String() string {
return (*llog.Severity)(s).String()
}
// ModuleSpec allows for the setting of specific log levels for specific
// modules. The syntax is recordio=2,file=1,gfs*=3
// It can be set via the ModuleSpec optional parameter to Configure.
// It implements the flag.Value interface to support command line option parsing.
type ModuleSpec struct {
llog.ModuleSpec
}
// FilepathSpec allows for the setting of specific log levels for specific
// files matched by a regular expression. The syntax is <re>=3,<re1>=2.
// It can be set via the FilepathSpec optional parameter to Configure.
// It implements the flag.Value interface to support command line option parsing.
type FilepathSpec struct {
llog.FilepathSpec
}
// TraceLocation specifies the location, file:N, which when encountered will
// cause logging to emit a stack trace.
// It can be set via the TraceLocation optional parameter to Configure.
// It implements the flag.Value interface to support command line option parsing.
type TraceLocation struct {
llog.TraceLocation
}
type Logger struct {
log *llog.Log
mu sync.Mutex // guards updates to the vars below.
autoFlush bool
maxStackBufSize int
logDir string
configured bool
}
func (l *Logger) maybeFlush() {
if l.autoFlush {
l.log.Flush()
}
}
var (
Log *Logger
ErrConfigured = errors.New("logger has already been configured")
)
const stackSkip = 1
func init() {
Log = &Logger{log: llog.NewLogger("vlog", stackSkip)}
}
// NewLogger creates a new instance of the logging interface.
func NewLogger(name string) *Logger {
// Create an instance of the runtime with just logging enabled.
return &Logger{log: llog.NewLogger(name, stackSkip)}
}
// Configure configures all future logging. Some options
// may not be usable if ConfigureLogging is called from an init function,
// in which case an error will be returned. The Configured error is returned
// if ConfigureLogger has already been called unless the
// OverridePriorConfiguration options is included.
func (l *Logger) Configure(opts ...LoggingOpts) error {
l.mu.Lock()
defer l.mu.Unlock()
override := false
for _, o := range opts {
switch v := o.(type) {
case OverridePriorConfiguration:
override = bool(v)
}
}
if l.configured && !override {
return ErrConfigured
}
for _, o := range opts {
switch v := o.(type) {
case AlsoLogToStderr:
l.log.SetAlsoLogToStderr(bool(v))
case Level:
l.log.SetV(llog.Level(v))
case LogDir:
l.logDir = string(v)
l.log.SetLogDir(l.logDir)
case LogToStderr:
l.log.SetLogToStderr(bool(v))
case MaxStackBufSize:
sz := int(v)
if sz > initialMaxStackBufSize {
l.maxStackBufSize = sz
l.log.SetMaxStackBufSize(sz)
}
case ModuleSpec:
l.log.SetVModule(v.ModuleSpec)
case FilepathSpec:
l.log.SetVFilepath(v.FilepathSpec)
case TraceLocation:
l.log.SetTraceLocation(v.TraceLocation)
case StderrThreshold:
l.log.SetStderrThreshold(llog.Severity(v))
case AutoFlush:
l.autoFlush = bool(v)
}
}
l.configured = true
return nil
}
// CopyStandardLogTo arranges for messages written to the Go "log" package's
// default logs to also appear in the Google logs for the named and lower
// severities. Subsequent changes to the standard log's default output location
// or format may break this behavior.
//
// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
// recognized, CopyStandardLogTo panics.
func (l *Logger) CopyStandardLogTo(name string) {
l.log.CopyStandardLogTo(name)
}
// LogDir returns the directory where the log files are written.
func (l *Logger) LogDir() string {
if len(l.logDir) != 0 {
return l.logDir
}
return os.TempDir()
}
// Stats returns stats on how many lines/bytes haven been written to
// this set of logs.
func (l *Logger) Stats() (Info, Error struct{ Lines, Bytes int64 }) {
stats := l.log.Stats()
return struct{ Lines, Bytes int64 }{Lines: stats.Info.Lines(), Bytes: stats.Info.Bytes()},
struct{ Lines, Bytes int64 }{Lines: stats.Error.Lines(), Bytes: stats.Error.Bytes()}
}
// Info logs to the INFO log.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func (l *Logger) Info(args ...interface{}) {
l.log.Print(llog.InfoLog, args...)
l.maybeFlush()
}
// Infof logs to the INFO log.
// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
func (l *Logger) Infof(format string, args ...interface{}) {
l.log.PrintfDepth(llog.InfoLog, 0, format, args...)
l.maybeFlush()
}
// InfoDepth acts as Info but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Info.
func (l *Logger) InfoDepth(depth int, args ...interface{}) {
l.log.PrintDepth(llog.InfoLog, depth, args...)
l.maybeFlush()
}
func infoStack(l *Logger, all bool) {
n := initialMaxStackBufSize
var trace []byte
for n <= l.maxStackBufSize {
trace = make([]byte, n)
nbytes := runtime.Stack(trace, all)
if nbytes < len(trace) {
l.log.PrintfDepth(llog.InfoLog, 0, "%s", trace[:nbytes])
return
}
n *= 2
}
l.log.PrintfDepth(llog.InfoLog, 0, "%s", trace)
l.maybeFlush()
}
// InfoStack logs the current goroutine's stack if the all parameter
// is false, or the stacks of all goroutines if it's true.
func (l *Logger) InfoStack(all bool) {
infoStack(l, all)
}
func (l *Logger) V(v int) bool {
return l.log.VDepth(0, llog.Level(v))
}
func (l *Logger) VDepth(depth int, v int) bool {
return l.log.VDepth(depth, llog.Level(v))
}
type discardInfo struct{}
func (*discardInfo) Info(...interface{}) {}
func (*discardInfo) Infof(string, ...interface{}) {}
func (*discardInfo) InfoDepth(int, ...interface{}) {}
func (*discardInfo) InfoStack(bool) {}
func (l *Logger) VI(v int) interface {
// Info logs to the INFO log.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
Info(args ...interface{})
// Infoln logs to the INFO log.
// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
Infof(format string, args ...interface{})
// InfoDepth acts as Info but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Info.
InfoDepth(depth int, args ...interface{})
// InfoStack logs the current goroutine's stack if the all parameter
// is false, or the stacks of all goroutines if it's true.
InfoStack(all bool)
} {
if l.log.VDepth(0, llog.Level(v)) {
return l
}
return &discardInfo{}
}
func (l *Logger) VIDepth(depth int, v int) interface {
// Info logs to the INFO log.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
Info(args ...interface{})
// Infoln logs to the INFO log.
// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
Infof(format string, args ...interface{})
// InfoDepth acts as Info but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Info.
InfoDepth(depth int, args ...interface{})
// InfoStack logs the current goroutine's stack if the all parameter
// is false, or the stacks of all goroutines if it's true.
InfoStack(all bool)
} {
if l.log.VDepth(depth, llog.Level(v)) {
return l
}
return &discardInfo{}
}
// Flush flushes all pending log I/O.
func (l *Logger) FlushLog() {
l.log.Flush()
}
// Error logs to the ERROR and INFO logs.
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func (l *Logger) Error(args ...interface{}) {
l.log.Print(llog.ErrorLog, args...)
l.maybeFlush()
}
// ErrorDepth acts as Error but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Error.
func (l *Logger) ErrorDepth(depth int, args ...interface{}) {
l.log.PrintDepth(llog.ErrorLog, depth, args...)
l.maybeFlush()
}
// Errorf logs to the ERROR and INFO logs.
// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
func (l *Logger) Errorf(format string, args ...interface{}) {
l.log.PrintfDepth(llog.ErrorLog, 0, format, args...)
l.maybeFlush()
}
// Fatal logs to the FATAL, ERROR and INFO logs,
// including a stack trace of all running goroutines, then calls os.Exit(255).
// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
func (l *Logger) Fatal(args ...interface{}) {
l.log.Print(llog.FatalLog, args...)
}
// FatalDepth acts as Fatal but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Fatal.
func (l *Logger) FatalDepth(depth int, args ...interface{}) {
l.log.PrintDepth(llog.FatalLog, depth, args...)
}
// Fatalf logs to the FATAL, ERROR and INFO logs,
// including a stack trace of all running goroutines, then calls os.Exit(255).
// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
func (l *Logger) Fatalf(format string, args ...interface{}) {
l.log.PrintfDepth(llog.FatalLog, 0, format, args...)
}
// Panic is equivalent to Error() followed by a call to panic().
func (l *Logger) Panic(args ...interface{}) {
l.Error(args...)
panic(fmt.Sprint(args...))
}
// PanicDepth acts as Panic but uses depth to determine which call frame to log.
// A depth of 0 is equivalent to calling Panic.
func (l *Logger) PanicDepth(depth int, args ...interface{}) {
l.ErrorDepth(depth, args...)
panic(fmt.Sprint(args...))
}
// Panicf is equivalent to Errorf() followed by a call to panic().
func (l *Logger) Panicf(format string, args ...interface{}) {
l.Errorf(format, args...)
panic(fmt.Sprintf(format, args...))
}