/
standard.go
416 lines (348 loc) · 10.7 KB
/
standard.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package logger
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
logging "github.com/keybase/go-logging"
"golang.org/x/net/context"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
const permDir os.FileMode = 0700
// Map from module name to whether SetLevel() has been called for that
// module.
var initLoggingSetLevelCalled = map[string]struct{}{}
// Protects access to initLoggingSetLevelCalled and the actual
// SetLevel call.
var initLoggingSetLevelMutex sync.Mutex
// CtxStandardLoggerKey is a type defining context keys used by the
// Standard logger.
type CtxStandardLoggerKey int
const (
// CtxLogTagsKey defines a context key that can associate with a map of
// context keys (key -> descriptive-name), the mapped values of which should
// be logged by a Standard logger if one of those keys is seen in a context
// during a log call.
CtxLogTagsKey CtxStandardLoggerKey = iota
)
type CtxLogTags map[interface{}]string
// NewContext returns a new Context that carries adds the given log
// tag mappings (context key -> display string).
func NewContextWithLogTags(
ctx context.Context, logTagsToAdd CtxLogTags) context.Context {
currTags, _ := LogTagsFromContext(ctx)
newTags := make(CtxLogTags)
// Make a copy to avoid races
for key, tag := range currTags {
newTags[key] = tag
}
for key, tag := range logTagsToAdd {
newTags[key] = tag
}
return context.WithValue(ctx, CtxLogTagsKey, newTags)
}
// LogTagsFromContext returns the log tags being passed along with the
// given context.
func LogTagsFromContext(ctx context.Context) (CtxLogTags, bool) {
logTags, ok := ctx.Value(CtxLogTagsKey).(CtxLogTags)
return logTags, ok
}
// LogTagsFromContextRPC is a wrapper around LogTagsFromContext
// that simply casts the result to the type expected by
// rpc.Connection.
func LogTagsFromContextRPC(ctx context.Context) (map[interface{}]string, bool) {
tags, ok := LogTagsFromContext(ctx)
return map[interface{}]string(tags), ok
}
type rpcTagKey string
// ConvertRPCTagsToLogTags takes any RPC tags in the context and makes
// them log tags. It uses the string representation of the tag key,
// rather than the original uniquely typed key, since the latter isn't
// available in the RPC tags.
func ConvertRPCTagsToLogTags(ctx context.Context) context.Context {
rpcTags, ok := rpc.RpcTagsFromContext(ctx)
if !ok {
return ctx
}
tags := make(CtxLogTags)
for key, value := range rpcTags {
// The map key should be a proper unique type, but that's not
// passed along in the RPC so just use our own string-like type.
tags[rpcTagKey(key)] = key
ctx = context.WithValue(ctx, rpcTagKey(key), value)
}
ctx = context.WithValue(ctx, rpc.CtxRpcTagsKey, nil)
return NewContextWithLogTags(ctx, tags)
}
type ExternalLogger interface {
Log(level keybase1.LogLevel, format string, args []interface{})
}
type entry struct {
level keybase1.LogLevel
format string
args []interface{}
}
type Standard struct {
internal *logging.Logger
filename string
configureMutex sync.Mutex
module string
externalHandler ExternalHandler
}
// Verify Standard fully implements the Logger interface.
var _ Logger = (*Standard)(nil)
// New creates a new Standard logger for module.
func New(module string) *Standard {
return NewWithCallDepth(module, 0)
}
// NewWithCallDepth creates a new Standard logger for module, and when
// printing file names and line numbers, it goes extraCallDepth up the
// stack from where logger was invoked.
func NewWithCallDepth(module string, extraCallDepth int) *Standard {
log := logging.MustGetLogger(module)
log.ExtraCalldepth = 1 + extraCallDepth
ret := &Standard{
internal: log,
module: module,
}
ret.setLogLevelInfo()
return ret
}
func (log *Standard) setLogLevelInfo() {
initLoggingSetLevelMutex.Lock()
defer initLoggingSetLevelMutex.Unlock()
if _, found := initLoggingSetLevelCalled[log.module]; !found {
logging.SetLevel(logging.INFO, log.module)
initLoggingSetLevelCalled[log.module] = struct{}{}
}
}
func prepareString(
ctx context.Context, fmts string) string {
if ctx == nil {
return fmts
}
logTags, ok := LogTagsFromContext(ctx)
if !ok || len(logTags) == 0 {
return fmts
}
var tags []string
for key, tag := range logTags {
if v := ctx.Value(key); v != nil {
tags = append(tags, fmt.Sprintf("%s=%s", tag, v))
}
}
return fmts + " [tags:" + strings.Join(tags, ",") + "]"
}
func (log *Standard) Debug(fmt string, arg ...interface{}) {
log.internal.Debugf(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_DEBUG, fmt, arg)
}
}
func (log *Standard) CDebugf(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.DEBUG) {
log.CloneWithAddedDepth(1).Debug(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Info(fmt string, arg ...interface{}) {
log.internal.Infof(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_INFO, fmt, arg)
}
}
func (log *Standard) CInfof(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.INFO) {
log.CloneWithAddedDepth(1).Info(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Notice(fmt string, arg ...interface{}) {
log.internal.Noticef(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_NOTICE, fmt, arg)
}
}
func (log *Standard) CNoticef(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.NOTICE) {
log.CloneWithAddedDepth(1).Notice(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Warning(fmt string, arg ...interface{}) {
log.internal.Warningf(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_WARN, fmt, arg)
}
}
func (log *Standard) CWarningf(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.WARNING) {
log.CloneWithAddedDepth(1).Warning(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Error(fmt string, arg ...interface{}) {
log.internal.Errorf(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_ERROR, fmt, arg)
}
}
func (log *Standard) Errorf(fmt string, arg ...interface{}) {
log.CloneWithAddedDepth(1).Error(fmt, arg...)
}
func (log *Standard) CErrorf(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.ERROR) {
log.CloneWithAddedDepth(1).Error(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Critical(fmt string, arg ...interface{}) {
log.internal.Criticalf(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_CRITICAL, fmt, arg)
}
}
func (log *Standard) CCriticalf(ctx context.Context, fmt string,
arg ...interface{}) {
if log.internal.IsEnabledFor(logging.CRITICAL) {
log.CloneWithAddedDepth(1).Critical(prepareString(ctx, fmt), arg...)
}
}
func (log *Standard) Fatalf(fmt string, arg ...interface{}) {
log.internal.Fatalf(fmt, arg...)
if log.externalHandler != nil {
log.externalHandler.Log(keybase1.LogLevel_FATAL, fmt, arg)
}
}
func (log *Standard) CFatalf(ctx context.Context, fmt string,
arg ...interface{}) {
log.CloneWithAddedDepth(1).Fatalf(prepareString(ctx, fmt), arg...)
}
func (log *Standard) Profile(fmts string, arg ...interface{}) {
log.CloneWithAddedDepth(1).Debug(fmts, arg...)
}
// Configure sets the style of the log file, whether debugging (verbose)
// is enabled and a filename. If a filename is provided here it will
// be used for logging straight away (this is a new feature).
// SetLogFileConfig provides a way to set the log file with more control on rotation.
func (log *Standard) Configure(style string, debug bool, filename string) {
log.configureMutex.Lock()
defer log.configureMutex.Unlock()
log.filename = filename
var logfmt string
globalLock.Lock()
isTerm := stderrIsTerminal
globalLock.Unlock()
// TODO: how should setting the log file after a Configure be handled?
if isTerm {
if debug {
logfmt = fancyFormat
} else {
logfmt = defaultFormat
}
} else {
logfmt = fileFormat
}
// Override the format above if an explicit style was specified.
switch style {
case "default":
logfmt = defaultFormat // Default
case "plain":
logfmt = plainFormat // Plain
case "file":
logfmt = fileFormat // Good for logging to files
case "fancy":
logfmt = fancyFormat // Fancy, good for terminals with color
}
if debug {
logging.SetLevel(logging.DEBUG, log.module)
}
logging.SetFormatter(logging.MustStringFormatter(logfmt))
}
func OpenLogFile(filename string) (name string, file *os.File, err error) {
name = filename
if err = MakeParentDirs(name); err != nil {
return
}
file, err = os.OpenFile(name, (os.O_APPEND | os.O_WRONLY | os.O_CREATE), 0600)
if err != nil {
return
}
return
}
func FileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func MakeParentDirs(filename string) error {
dir, _ := filepath.Split(filename)
// If passed a plain file name as a path
if dir == "" {
return nil
}
exists, err := FileExists(dir)
if err != nil {
return err
}
if !exists {
err = os.MkdirAll(dir, permDir)
if err != nil {
return err
}
}
return nil
}
func PickFirstError(errors ...error) error {
for _, e := range errors {
if e != nil {
return e
}
}
return nil
}
func (log *Standard) CloneWithAddedDepth(depth int) Logger {
clone := Standard{
filename: log.filename,
module: log.module,
externalHandler: log.externalHandler,
}
cloneInternal := *log.internal
clone.internal = &cloneInternal
clone.internal.ExtraCalldepth = log.internal.ExtraCalldepth + depth
return &clone
}
func (log *Standard) SetExternalHandler(handler ExternalHandler) {
log.externalHandler = handler
}
type UnforwardedLogger Standard
func (log *Standard) GetUnforwardedLogger() *UnforwardedLogger {
return (*UnforwardedLogger)(log)
}
func (log *UnforwardedLogger) Debug(s string, args ...interface{}) {
log.internal.Debugf(s, args...)
}
func (log *UnforwardedLogger) Error(s string, args ...interface{}) {
log.internal.Errorf(s, args...)
}
func (log *UnforwardedLogger) Errorf(s string, args ...interface{}) {
log.internal.Errorf(s, args...)
}
func (log *UnforwardedLogger) Warning(s string, args ...interface{}) {
log.internal.Warningf(s, args...)
}
func (log *UnforwardedLogger) Info(s string, args ...interface{}) {
log.internal.Infof(s, args...)
}
func (log *UnforwardedLogger) Profile(s string, args ...interface{}) {
log.internal.Debugf(s, args...)
}