-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollbar.go
103 lines (89 loc) · 2.05 KB
/
rollbar.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
package utils
import (
"runtime"
"strings"
"github.com/pkg/errors"
"github.com/stvp/rollbar"
"net/http"
"fmt"
)
type stackTracer interface {
StackTrace() errors.StackTrace
}
func errorsToRollbarStack(st stackTracer) rollbar.Stack {
t := st.StackTrace()
rs := make(rollbar.Stack, len(t))
for i, f := range t {
// Program counter as it's computed internally in errors.Frame
pc := uintptr(f) - 1
fn := runtime.FuncForPC(pc)
if fn == nil {
rs[i] = rollbar.Frame{
Filename: "unknown",
Method: "?",
Line: 0,
}
continue
}
// symtab info
file, line := fn.FileLine(pc)
name := fn.Name()
// trim compile time GOPATH from file name
fileWImportPath := trimGOPATH(name, file)
// Strip only method name from FQN
idx := strings.LastIndex(name, "/")
name = name[idx+1:]
idx = strings.Index(name, ".")
name = name[idx+1:]
rs[i] = rollbar.Frame{
Filename: fileWImportPath,
Method: name,
Line: line,
}
}
return rs
}
// Taken AS IS from errors pkg since it's not exported there.
// Check out the source code with good comments on https://github.com/pkg/errors/blob/master/stack.go
func trimGOPATH(name, file string) string {
const sep = "/"
goal := strings.Count(name, sep) + 2
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
i = -len(sep)
break
}
}
file = file[i+len(sep):]
return file
}
func LogRequestError(r *http.Request, err error) {
st, ok := err.(stackTracer)
if ok {
fmt.Printf("%s: %+v\n", st, st.StackTrace())
}
// Log if we have a token setup
if len(rollbar.Token) != 0 {
if ok {
rollbar.RequestErrorWithStack(rollbar.ERR, r, err, errorsToRollbarStack(st))
} else {
rollbar.RequestError(rollbar.ERR, r, err)
}
}
}
func LogError(err error) {
st, ok := err.(stackTracer)
if ok {
fmt.Printf("%s: %+v\n", st, st.StackTrace())
}
// Log if we have a token setup
if len(rollbar.Token) != 0 {
if ok {
rollbar.ErrorWithStack(rollbar.ERR, err, errorsToRollbarStack(st))
} else {
rollbar.Error(rollbar.ERR, err)
}
}
}