-
Notifications
You must be signed in to change notification settings - Fork 1
/
servicelog.go
87 lines (74 loc) · 2.01 KB
/
servicelog.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
package apexovernsq
import (
"errors"
"fmt"
"os"
"path"
"sort"
"sync"
"github.com/apex/log"
)
func processName() string {
return path.Base(os.Args[0])
}
func appendServiceFieldsToEntry(entry *log.Entry) *log.Entry {
hostname, err := os.Hostname()
if err != nil {
log.WithError(err).Warn("Unable to get hostname for service logging")
}
return entry.WithFields(
log.Fields{
"service": processName(),
"hostname": hostname,
"pid": fmt.Sprintf("%d", os.Getpid()),
})
}
// Create a new logging context with service information.
func NewApexLogServiceContext() *log.Entry {
logger, _ := log.Log.(*log.Logger)
entry := log.NewEntry(logger)
return appendServiceFieldsToEntry(entry)
}
// Create a new logging context, with a handler that isn't the default handler and with service information appended.
func NewApexLogServiceContextWithHandler(handler log.Handler) *log.Entry {
logger := &log.Logger{
Handler: handler,
Level: log.Log.(*log.Logger).Level,
}
entry := log.NewEntry(logger)
return appendServiceFieldsToEntry(entry)
}
type ServiceFilterApexLogHandler struct {
mu sync.Mutex
filter *[]string
handler log.Handler
}
func NewApexLogServiceFilterHandler(handler log.Handler, filter *[]string) *ServiceFilterApexLogHandler {
if filter != nil {
sort.Strings(*filter)
}
return &ServiceFilterApexLogHandler{
handler: handler,
filter: filter,
}
}
func (h *ServiceFilterApexLogHandler) shouldLog(e *log.Entry, serviceName string) bool {
if h.filter == nil || len(*h.filter) == 0 || serviceName == "" {
return true
}
index := sort.SearchStrings(*h.filter, serviceName)
return index < len(*h.filter) && (*h.filter)[index] == serviceName
}
func (h *ServiceFilterApexLogHandler) HandleLog(e *log.Entry) error {
h.mu.Lock()
defer h.mu.Unlock()
field := e.Fields.Get("service")
serviceName, ok := field.(string)
if ok {
if h.shouldLog(e, serviceName) {
return h.handler.HandleLog(e)
}
return nil
}
return errors.New("Entry had a service name that was not a string")
}