-
Notifications
You must be signed in to change notification settings - Fork 62
/
graylog_hook.go
294 lines (256 loc) · 7.21 KB
/
graylog_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
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
package graylog
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/sirupsen/logrus"
)
const StackTraceKey = "_stacktrace"
// Set graylog.BufSize = <value> _before_ calling NewGraylogHook
// Once the buffer is full, logging will start blocking, waiting for slots to
// be available in the queue.
var BufSize uint = 8192
// GraylogHook to send logs to a logging service compatible with the Graylog API and the GELF format.
type GraylogHook struct {
Extra map[string]interface{}
Host string
Level logrus.Level
gelfLogger GELFWriter
buf chan graylogEntry
wg sync.WaitGroup
mu sync.RWMutex
synchronous bool
blacklist map[string]bool
}
// Graylog needs file and line params
type graylogEntry struct {
*logrus.Entry
file string
line int
}
// NewGraylogHook creates a hook to be added to an instance of logger.
func NewGraylogHook(addr string, extra map[string]interface{}) *GraylogHook {
g, err := NewWriter(addr)
if err != nil {
logrus.WithError(err).Error("Can't create Gelf logger")
}
host, err := os.Hostname()
if err != nil {
host = "localhost"
}
hook := &GraylogHook{
Host: host,
Extra: extra,
Level: logrus.DebugLevel,
gelfLogger: g,
synchronous: true,
}
return hook
}
// NewAsyncGraylogHook creates a hook to be added to an instance of logger.
// The hook created will be asynchronous, and it's the responsibility of the user to call the Flush method
// before exiting to empty the log queue.
func NewAsyncGraylogHook(addr string, extra map[string]interface{}) *GraylogHook {
g, err := NewWriter(addr)
if err != nil {
logrus.WithError(err).Error("Can't create Gelf logger")
}
host, err := os.Hostname()
if err != nil {
host = "localhost"
}
hook := &GraylogHook{
Host: host,
Extra: extra,
Level: logrus.DebugLevel,
gelfLogger: g,
buf: make(chan graylogEntry, BufSize),
}
go hook.fire() // Log in background
return hook
}
// Fire is called when a log event is fired.
// We assume the entry will be altered by another hook,
// otherwise we might be logging something wrong to Graylog
func (hook *GraylogHook) Fire(entry *logrus.Entry) error {
hook.mu.RLock() // Claim the mutex as a RLock - allowing multiple go routines to log simultaneously
defer hook.mu.RUnlock()
var file string
var line int
if entry.Caller != nil {
file = entry.Caller.File
line = entry.Caller.Line
}
newData := make(map[string]interface{})
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
newData[k] = v.Error()
default:
newData[k] = v
}
}
newEntry := &logrus.Entry{
Logger: entry.Logger,
Data: newData,
Time: entry.Time,
Level: entry.Level,
Caller: entry.Caller,
Message: entry.Message,
}
gEntry := graylogEntry{newEntry, file, line}
if hook.synchronous {
hook.sendEntry(gEntry)
} else {
hook.wg.Add(1)
hook.buf <- gEntry
}
return nil
}
// Flush waits for the log queue to be empty.
// This func is meant to be used when the hook was created with NewAsyncGraylogHook.
func (hook *GraylogHook) Flush() {
hook.mu.Lock() // claim the mutex as a Lock - we want exclusive access to it
defer hook.mu.Unlock()
hook.wg.Wait()
}
// fire will loop on the 'buf' channel, and write entries to graylog
func (hook *GraylogHook) fire() {
for {
entry := <-hook.buf // receive new entry on channel
hook.sendEntry(entry)
hook.wg.Done()
}
}
func logrusLevelToSyslog(level logrus.Level) int32 {
const (
LOG_EMERG = 0 /* system is unusable */
LOG_ALERT = 1 /* action must be taken immediately */
LOG_CRIT = 2 /* critical conditions */
LOG_ERR = 3 /* error conditions */
LOG_WARNING = 4 /* warning conditions */
LOG_NOTICE = 5 /* normal but significant condition */
LOG_INFO = 6 /* informational */
LOG_DEBUG = 7 /* debug-level messages */
)
// logrus has no equivalent of syslog LOG_NOTICE
switch level {
case logrus.PanicLevel:
return LOG_ALERT
case logrus.FatalLevel:
return LOG_CRIT
case logrus.ErrorLevel:
return LOG_ERR
case logrus.WarnLevel:
return LOG_WARNING
case logrus.InfoLevel:
return LOG_INFO
case logrus.DebugLevel, logrus.TraceLevel:
return LOG_DEBUG
default:
return LOG_DEBUG
}
}
// sendEntry sends an entry to graylog synchronously
func (hook *GraylogHook) sendEntry(entry graylogEntry) {
if hook.gelfLogger == nil {
fmt.Println("Can't connect to Graylog")
return
}
w := hook.gelfLogger
// remove trailing and leading whitespace
p := bytes.TrimSpace([]byte(entry.Message))
// If there are newlines in the message, use the first line
// for the short message and set the full message to the
// original input. If the input has no newlines, stick the
// whole thing in Short.
short := p
full := []byte("")
if i := bytes.IndexRune(p, '\n'); i > 0 {
short = p[:i]
full = p
}
level := logrusLevelToSyslog(entry.Level)
// Don't modify entry.Data directly, as the entry will used after this hook was fired
extra := map[string]interface{}{}
// Merge extra fields
for k, v := range hook.Extra {
k = fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field."
extra[k] = v
}
if entry.Caller != nil {
extra["_file"] = entry.Caller.File
extra["_line"] = entry.Caller.Line
extra["_function"] = entry.Caller.Function
}
for k, v := range entry.Data {
if !hook.blacklist[k] {
extraK := fmt.Sprintf("_%s", k) // "[...] every field you send and prefix with a _ (underscore) will be treated as an additional field."
if k == logrus.ErrorKey {
asError, isError := v.(error)
_, isMarshaler := v.(json.Marshaler)
if isError && !isMarshaler {
extra[extraK] = newMarshalableError(asError)
} else {
extra[extraK] = v
}
if stackTrace := extractStackTrace(asError); stackTrace != nil {
extra[StackTraceKey] = fmt.Sprintf("%+v", stackTrace)
}
} else {
extra[extraK] = v
}
}
}
m := Message{
Version: "1.1",
Host: hook.Host,
Short: string(short),
Full: string(full),
TimeUnix: float64(time.Now().UnixNano()/1000000) / 1000.,
Level: level,
File: entry.file,
Line: entry.line,
Extra: extra,
}
if err := w.WriteMessage(&m); err != nil {
fmt.Println(err)
}
}
// Levels returns the available logging levels.
func (hook *GraylogHook) Levels() []logrus.Level {
levels := []logrus.Level{}
for _, level := range logrus.AllLevels {
if level <= hook.Level {
levels = append(levels, level)
}
}
return levels
}
// Blacklist create a blacklist map to filter some message keys.
// This useful when you want your application to log extra fields locally
// but don't want graylog to store them.
func (hook *GraylogHook) Blacklist(b []string) {
hook.blacklist = make(map[string]bool)
for _, elem := range b {
hook.blacklist[elem] = true
}
}
// SetWriter sets the hook Gelf writer
func (hook *GraylogHook) SetWriter(w *LowLevelProtocolWriter) error {
if w == nil {
return errors.New("writer can't be nil")
}
hook.gelfLogger = w
return nil
}
// Writer returns the writer
func (hook *GraylogHook) Writer() GELFWriter {
return hook.gelfLogger
}