-
Notifications
You must be signed in to change notification settings - Fork 0
/
logrus.go
60 lines (48 loc) · 1.75 KB
/
logrus.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
package pubsubx
import (
"github.com/ThreeDotsLabs/watermill"
"github.com/sirupsen/logrus"
)
// LogrusLoggerAdapter is a logrus adapter for watermill.
type LogrusLoggerAdapter struct {
log *logrus.Logger
fields watermill.LogFields
}
// NewLogrusLogger returns a LogrusLoggerAdapter that sends all logs to
// the passed logrus instance.
func NewLogrusLogger(log *logrus.Logger) watermill.LoggerAdapter {
return &LogrusLoggerAdapter{log: log}
}
// Error logs on level error with err as field and optional fields.
func (l *LogrusLoggerAdapter) Error(msg string, err error, fields watermill.LogFields) {
l.createEntry(fields.Add(watermill.LogFields{"err": err})).Error(msg)
}
// Info logs on level info with optional fields.
func (l *LogrusLoggerAdapter) Info(msg string, fields watermill.LogFields) {
l.createEntry(fields).Info(msg)
}
// Debug logs on level debug with optional fields.
func (l *LogrusLoggerAdapter) Debug(msg string, fields watermill.LogFields) {
l.createEntry(fields).Debug(msg)
}
// Trace logs on level trace with optional fields.
func (l *LogrusLoggerAdapter) Trace(msg string, fields watermill.LogFields) {
l.createEntry(fields).Trace(msg)
}
// With returns a new LogrusLoggerAdapter that includes fields
// to be re-used between logging statements.
func (l *LogrusLoggerAdapter) With(fields watermill.LogFields) watermill.LoggerAdapter {
return &LogrusLoggerAdapter{
log: l.log,
fields: l.fields.Add(fields),
}
}
// createEntry is a helper to add fields to a logrus entry if necessary.
func (l *LogrusLoggerAdapter) createEntry(fields watermill.LogFields) *logrus.Entry {
entry := logrus.NewEntry(l.log)
allFields := fields.Add(l.fields)
if len(allFields) > 0 {
entry = entry.WithFields(logrus.Fields(allFields))
}
return entry
}