forked from sebest/logrusly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.go
117 lines (99 loc) · 2.45 KB
/
hook.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
package logrusly
import (
"strings"
"github.com/Sirupsen/logrus"
"github.com/segmentio/go-loggly"
)
// LogglyHook to send logs to the Loggly service.
type LogglyHook struct {
client *loggly.Client
host string
levels []logrus.Level
}
const (
// RFC3339Micro represents microseconds/seconds fraction (6 digits)
// that can be automatically parse by Loggly
RFC3339Micro = "2006-01-02T15:04:05.999999Z07:00"
)
// NewLogglyHook creates a Loogly hook to be added to an instance of logger.
func NewLogglyHook(token string, host string, level logrus.Level, tags ...string) *LogglyHook {
client := loggly.New(token, tags...)
client.Defaults = loggly.Message{}
// sigc := make(chan os.Signal, 1)
// signal.Notify(sigc,
// syscall.SIGHUP,
// syscall.SIGINT,
// syscall.SIGTERM,
// syscall.SIGQUIT)
// go func() {
// s := <-sigc
// if s != nil {
// client.Flush()
// }
// }()
levels := []logrus.Level{}
for _, l := range []logrus.Level{
logrus.PanicLevel,
logrus.FatalLevel,
logrus.ErrorLevel,
logrus.WarnLevel,
logrus.InfoLevel,
logrus.DebugLevel,
} {
if l <= level {
levels = append(levels, l)
}
}
return &LogglyHook{
client: client,
host: host,
levels: levels,
}
}
// Tag exposes the go-loggly .Tag() functionality
func (hook *LogglyHook) Tag(tags string) {
hook.client.Tag(tags)
}
// Fire sends the event to Loggly
func (hook *LogglyHook) Fire(entry *logrus.Entry) error {
data := make(logrus.Fields, len(entry.Data))
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
level := entry.Level.String()
logglyMessage := loggly.Message{
"timestamp": entry.Time.UTC().Format(RFC3339Micro),
"level": strings.ToUpper(level),
"message": entry.Message,
"host": hook.host,
"data": data,
}
err := hook.client.Send(logglyMessage)
if err != nil {
log := logrus.New()
log.WithFields(logrus.Fields{
"source": "loggly",
"error": err.Error(),
}).Warn("Failed to send error to Loggly")
return err
}
if level == "fatal" || level == "panic" {
hook.Flush()
}
return nil
}
// Flush sends buffered events to Loggly.
func (hook *LogglyHook) Flush() {
hook.client.Flush()
}
// Levels returns the list of logging levels that we want to send to Loggly.
func (hook *LogglyHook) Levels() []logrus.Level {
return hook.levels
}