forked from tokopedia/panics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
panics.go
216 lines (184 loc) · 4.36 KB
/
panics.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
package panics
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"runtime/debug"
"strings"
"github.com/julienschmidt/httprouter"
)
var (
env string
filepath string
slackWebhook string
slackChannel string
tagString string
)
type Tags map[string]string
type Options struct {
Env string
Filepath string
SentryDSN string
SlackWebhook string
SlackChannel string
Tags Tags
}
func SetOptions(o *Options) {
filepath = o.Filepath
slackWebhook = o.SlackWebhook
slackChannel = o.SlackChannel
env = o.Env
var tmp []string
for key, val := range o.Tags {
tmp = append(tmp, fmt.Sprintf("`%s: %s`", key, val))
}
tagString = strings.Join(tmp, " | ")
}
func init() {
env = os.Getenv("TKPENV")
}
// CaptureHandler handle panic on http handler.
func CaptureHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
request, _ := httputil.DumpRequest(r, true)
defer func() {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
publishError(err, request, true)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
h.ServeHTTP(w, r)
}
}
// CaptureHTTPRouterHandler handle panic on httprouter handler.
func CaptureHTTPRouterHandler(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var err error
request, _ := httputil.DumpRequest(r, true)
defer func() {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
publishError(err, request, true)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
h(w, r, ps)
}
}
// CaptureNegroniHandler handle panic on negroni handler.
func CaptureNegroniHandler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
var err error
request, _ := httputil.DumpRequest(r, true)
defer func() {
r := recover()
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
publishError(err, request, true)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
next(w, r)
}
// Capture will publish any errors
func Capture(err string, message ...string) {
var tmp string
for i, val := range message {
if i == 0 {
tmp += val
} else {
tmp += fmt.Sprintf("\n\n%s", val)
}
}
publishError(errors.New(err), []byte(tmp), false)
}
func publishError(errs error, reqBody []byte, withStackTrace bool) {
var text string
var snip string
var buffer bytes.Buffer
errorStack := debug.Stack()
buffer.WriteString(fmt.Sprintf(`[%s] *%s*`, env, errs.Error()))
if len(tagString) > 0 {
buffer.WriteString(" | " + tagString)
}
if reqBody != nil {
buffer.WriteString(fmt.Sprintf(" ```%s``` ", string(reqBody)))
}
text = buffer.String()
if errorStack != nil && withStackTrace {
snip = fmt.Sprintf("```\n%s```", string(errorStack))
}
if slackWebhook != "" {
go postToSlack(buffer.String(), snip)
}
if filepath != "" {
go func() {
fp := fmt.Sprintf("%s/panics.log", filepath)
file, err := os.OpenFile(fp, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
log.Printf("[panics] failed to open file %s", fp)
return
}
file.Write([]byte(text))
file.Write([]byte(snip + "\r\n"))
file.Close()
}()
}
}
func postToSlack(text, snip string) {
payload := map[string]interface{}{
"text": text,
"attachments": []map[string]interface{}{
map[string]interface{}{
"text": snip,
"mrkdwn_in": []string{"text"},
},
},
}
if slackChannel != "" {
payload["channel"] = slackChannel
}
b, _ := json.Marshal(payload)
resp, err := http.DefaultClient.Post(slackWebhook, "application/json", bytes.NewBuffer(b))
if err != nil {
log.Printf("[panics] error on capturing error : %s \n", err.Error())
}
if resp.StatusCode >= 300 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("[panics] error on capturing error : %s \n", err)
return
}
log.Printf("[panics] error on capturing error : %s \n", string(b))
}
}