forked from archdx/zerolog-sentry
-
Notifications
You must be signed in to change notification settings - Fork 3
/
writer.go
200 lines (164 loc) · 4.26 KB
/
writer.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
// Package zlogsentry provides a zerolog writer which sends selected events to sentry.
package zlogsentry
import (
"errors"
"io"
"time"
"unsafe"
"github.com/buger/jsonparser"
"github.com/getsentry/sentry-go"
"github.com/rs/zerolog"
)
var levelsMapping = map[zerolog.Level]sentry.Level{
zerolog.DebugLevel: sentry.LevelDebug,
zerolog.InfoLevel: sentry.LevelInfo,
zerolog.WarnLevel: sentry.LevelWarning,
zerolog.ErrorLevel: sentry.LevelError,
zerolog.FatalLevel: sentry.LevelFatal,
zerolog.PanicLevel: sentry.LevelFatal,
}
var _ io.WriteCloser = new(Writer)
var now = time.Now
type Writer struct {
client *sentry.Client
levels map[zerolog.Level]struct{}
specialFields map[string]SpecialFieldType
flushTimeout time.Duration
name string
}
func New(client *sentry.Client, opts ...WriterOption) (*Writer, error) {
return NewWithName(client, "zerolog", opts...)
}
func NewWithName(client *sentry.Client, name string, opts ...WriterOption) (*Writer, error) {
cfg := newDefaultConfig()
for _, opt := range opts {
opt(&cfg)
}
levels := make(map[zerolog.Level]struct{}, len(cfg.levels))
for _, lvl := range cfg.levels {
levels[lvl] = struct{}{}
}
specialFields := make(map[string]SpecialFieldType, len(cfg.specialFields))
for k, t := range cfg.specialFields {
specialFields[k] = t
}
return &Writer{
client: client,
levels: levels,
specialFields: specialFields,
flushTimeout: cfg.flushTimeout,
name: name,
}, nil
}
func (w *Writer) Write(data []byte) (int, error) {
event, hint, err := w.parseLogEvent(data)
if err == nil {
w.client.CaptureEvent(event, hint, nil)
// should flush before os.Exit
if event.Level == sentry.LevelFatal {
w.client.Flush(w.flushTimeout)
}
}
return len(data), nil
}
func (w *Writer) Close() error {
w.client.Flush(w.flushTimeout)
return nil
}
func (w *Writer) parseLogEvent(data []byte) (event *sentry.Event, eventHint *sentry.EventHint, err error) {
sentryLvl, err := w.extractSentryLvl(data)
if err != nil {
return
}
event = &sentry.Event{
Timestamp: now(),
Level: sentryLvl,
Logger: w.name,
Extra: map[string]interface{}{},
Tags: map[string]string{},
}
eventHint = &sentry.EventHint{}
err = jsonparser.ObjectEach(data, func(keyRaw, valueRaw []byte, vt jsonparser.ValueType, offset int) error {
key := string(keyRaw)
// value := string(valueRaw)
value := bytesToStrUnsafe(valueRaw)
switch key {
case zerolog.LevelFieldName, zerolog.TimestampFieldName:
case zerolog.MessageFieldName:
event.Message = value
case zerolog.ErrorFieldName:
event.Exception = append(event.Exception, sentry.Exception{
Value: value,
Stacktrace: newStacktrace(),
})
default:
// first check if field is of special type
specialType, ok := w.specialFields[key]
if !ok {
// not special => add to additional data
event.Extra[key] = value
return nil
}
switch specialType {
case SpecialFieldTag:
event.Tags[key] = value
case SpecialFieldUserID:
event.User = sentry.User{
ID: value,
}
}
}
return nil
})
return
}
func (w *Writer) extractSentryLvl(data []byte) (sentryLvl sentry.Level, err error) {
lvlStr, err := jsonparser.GetUnsafeString(data, zerolog.LevelFieldName)
if err != nil {
return
}
lvl, err := zerolog.ParseLevel(lvlStr)
if err != nil {
return
}
_, enabled := w.levels[lvl]
if !enabled {
err = errors.New("level disabled")
return
}
sentryLvl, ok := levelsMapping[lvl]
if !ok {
err = errors.New("no such sentry level")
return
}
return
}
func newStacktrace() *sentry.Stacktrace {
const (
module = "github.com/sveatlo/zerolog-sentry"
loggerModule = "github.com/rs/zerolog"
)
st := sentry.NewStacktrace()
threshold := len(st.Frames) - 1
// drop current module frames
for ; threshold > 0 && st.Frames[threshold].Module == module; threshold-- {
}
outer:
// try to drop zerolog module frames after logger call point
for i := threshold; i > 0; i-- {
if st.Frames[i].Module == loggerModule {
for j := i - 1; j >= 0; j-- {
if st.Frames[j].Module != loggerModule {
threshold = j
break outer
}
}
break
}
}
st.Frames = st.Frames[:threshold+1]
return st
}
func bytesToStrUnsafe(data []byte) string {
return *(*string)(unsafe.Pointer(&data))
}