-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbugsnag.go
306 lines (268 loc) · 6.82 KB
/
bugsnag.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
295
296
297
298
299
300
301
302
303
304
305
306
package bugsnag
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
const (
apiEndpoint = "notify.bugsnag.com"
VERSION = "0.0.1"
)
var (
defaultInfo = ¬ifierInfo{Name: "Bugsnag Go", Version: VERSION, Url: "https://github.com/pettyjamesm/bugsnag-go"}
)
type notifierInfo struct {
Name string `json:"name"`
Version string `json:"version"`
Url string `json:"url"`
}
type Context interface {
Name() string
SetUserId(userId string)
Notify(err interface{})
NotifyOnPanic(swallowPanic bool)
}
type Notifier interface {
Notify(err interface{})
SetReleaseStage(releaseStage string)
SetNotifyStages(notifyStages []string)
SetUseSSL(useSSL bool)
NewContext(contextName string) Context
SetMaxStackSize(maxSize uint)
NotifyOnPanic(swallowPanic bool)
WillNotify() bool
SentNotificationCount() uint64
UnsentNotificationCount() uint64
}
func NewNotifier(apiKey string) Notifier {
notifier := &restNotifier{
apiKey: apiKey,
info: defaultInfo,
releaseStage: "production",
notifyStages: []string{"production"},
useSSL: false,
stackSize: 50,
httpClient: &http.Client{},
queue: make(chan *bugsnagNotification, 10),
totalTriggered: uint64(0),
totalNotified: uint64(0),
}
notifier.invalidateWillNotify()
return notifier
}
type restNotifier struct {
apiKey string
info *notifierInfo
// Release Stage Information
releaseStage string
notifyStages []string
// Indicates whether the current releaseStage is in notifyStages or not
willNotify bool
// Indicates SSL connections should be used
useSSL bool
// Maximum stack trace size
stackSize uint
// Http Client
httpClient *http.Client
// Send queue
queue chan *bugsnagNotification
// Counters for Sent / Success
totalTriggered uint64
totalNotified uint64
}
func (notifier *restNotifier) String() string {
return fmt.Sprintf("BugsnagNotifier(%v)", *notifier)
}
func (notifier *restNotifier) SentNotificationCount() uint64 {
return notifier.totalNotified
}
func (notifier *restNotifier) UnsentNotificationCount() uint64 {
return notifier.totalTriggered - notifier.totalNotified
}
func (notifier *restNotifier) WillNotify() bool {
return notifier.willNotify
}
func (notifier *restNotifier) NotifyOnPanic(swallowPanic bool) {
if err := recover(); err != nil {
notifier.notify(err, nil, !swallowPanic)
if !swallowPanic {
panic(err)
}
}
}
func (notifier *restNotifier) Notify(err interface{}) {
notifier.notify(err, nil, false)
}
type errorType interface {
Error() string
}
type stringType interface {
String() string
}
func (notifier *restNotifier) notify(err interface{}, context *notifierContext, synchronous bool) {
notifier.totalTriggered++
if !notifier.willNotify {
return
}
var message string
switch err.(type) {
case errorType:
message = err.(errorType).Error()
case stringType:
message = err.(stringType).String()
default:
message = fmt.Sprintf("%+v", err)
}
exception := bugsnagException{
ErrorClass: getErrorTypeName(err),
Message: message,
StackTrace: getStackFrames(2, int(notifier.stackSize)),
}
event := bugsnagEvent{
ReleaseStage: notifier.releaseStage,
Exceptions: []bugsnagException{exception},
}
if context != nil {
event.UserId = context.userId
event.Context = context.name
}
notification := &bugsnagNotification{
ApiKey: notifier.apiKey,
NotifierInfo: notifier.info,
Events: []bugsnagEvent{event},
}
if synchronous {
notifier.dispatchSingle(notification)
} else {
notifier.queue <- notification
}
}
func (notifier *restNotifier) SetReleaseStage(releaseStage string) {
notifier.releaseStage = releaseStage
notifier.invalidateWillNotify()
}
func (notifier *restNotifier) SetNotifyStages(releaseStages []string) {
notifier.notifyStages = releaseStages
notifier.invalidateWillNotify()
}
func (notifier *restNotifier) invalidateWillNotify() {
result := false
if notifier.apiKey != "" {
for _, check := range notifier.notifyStages {
if check == notifier.releaseStage {
result = true
break
}
}
}
if result && !notifier.willNotify {
notifier.willNotify = result
go notifier.processQueue()
} else if !result && notifier.willNotify {
notifier.willNotify = result
notifier.queue <- nil
}
}
func (notifier *restNotifier) SetUseSSL(useSSL bool) {
notifier.useSSL = useSSL
}
func (notifier *restNotifier) NewContext(contextName string) Context {
return ¬ifierContext{notifier: notifier, name: contextName}
}
func (notifier *restNotifier) SetMaxStackSize(maxSize uint) {
notifier.stackSize = maxSize
}
func (notifier *restNotifier) processQueue() {
for notifier.willNotify {
notification := <-notifier.queue
if notifier.willNotify && notification != nil {
notifier.dispatchSingle(notification)
}
}
// Drain the channel if not notifying
for !notifier.willNotify {
select {
case _ = <-notifier.queue:
continue
default:
break
}
}
}
func (notifier *restNotifier) dispatchSingle(notification *bugsnagNotification) {
defer func() {
if err := recover(); err != nil {
log.Panicf("Failed to send bugsnag notification!\n\t%s\n", err)
}
}()
var (
url string
serialized []byte
response *http.Response
err error
)
if notifier.useSSL {
url = "https://" + apiEndpoint
} else {
url = "http://" + apiEndpoint
}
serialized, err = json.Marshal(notification)
if err != nil {
panic(err)
}
response, err = notifier.httpClient.Post(url, "application/json", bytes.NewReader(serialized))
if err != nil {
panic(err)
}
defer response.Body.Close()
switch response.StatusCode {
case 200:
// Successful dispatch, yay
notifier.totalNotified++
return
case 400:
// Something wrong with our JSON formatting
log.Printf("Invalid JSON Sent to Bugsnag: %s\n", string(serialized))
case 401:
// Invalid API Key
log.Printf("API Key '%s' is not a valid Bugsnag API Key!\n", notifier.apiKey)
case 413:
panic(fmt.Errorf("Bugsnag Rejected Notification due to Size (Payload: %d bytes)", len(serialized)))
case 429:
log.Printf("Bugsnag Rate-Limit Exceeded")
time.Sleep(time.Millisecond * 10)
default:
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Printf("Unknown Bugsnag Response: %s\n", response.Status)
} else {
log.Printf("Unknown Bugsnag Response: %s\n%s\n", response.Status, body)
}
}
}
type notifierContext struct {
notifier *restNotifier
userId string
name string
}
func (context *notifierContext) Name() string {
return context.name
}
func (context *notifierContext) Notify(err interface{}) {
context.notifier.notify(err, context, false)
}
func (context *notifierContext) NotifyOnPanic(swallowPanic bool) {
if err := recover(); err != nil {
context.notifier.notify(err, context, !swallowPanic)
if !swallowPanic {
panic(err)
}
}
}
func (context *notifierContext) SetUserId(userId string) {
context.userId = userId
}