-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlog.go
More file actions
59 lines (47 loc) · 1.23 KB
/
log.go
File metadata and controls
59 lines (47 loc) · 1.23 KB
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
package logger
import (
"fmt"
"time"
)
type Attrs map[string]interface{}
type Log struct {
Package string `json:"package"`
Level string `json:"level"`
Message string `json:"msg"`
Attrs *Attrs `json:"attrs"`
Time int64 `json:"time"`
Elapsed int64 `json:"elapsed"`
ElapsedNano int64 `json:"elapsed_nano"`
}
func (log *Log) End(msg string, args ...interface{}) {
v, attrs := SplitAttrs(args)
elapsed := Now() - log.Time
log.Attrs = attrs
log.Elapsed = elapsed / 1000000
log.ElapsedNano = elapsed
log.Message = fmt.Sprintf(msg, v...)
runtime.Log(log)
}
// SplitAttrs checks if the last item passed in v is an Attrs instance,
// if so it returns it separately. If not, v is returned as-is with a nil Attrs.
func SplitAttrs(v []interface{}) ([]interface{}, *Attrs) {
if len(v) == 0 {
return v, nil
}
attrs, ok := v[len(v)-1].(Attrs)
if !ok {
return v, nil
}
// Normalize error values to strings so they serialize correctly to JSON
for key, val := range attrs {
if err, ok := val.(error); ok {
attrs[key] = err.Error()
}
}
v = v[:len(v)-1]
return v, &attrs
}
// Now is a shortcut for returning the current time in Unix nanoseconds.
func Now() int64 {
return time.Now().UnixNano()
}