@error-reporting/go 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -2
- package/go.mod +3 -0
- package/package.json +16 -4
- package/sdk.go +163 -0
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @error-reporting/go
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
需要 Go 1.21 或以上。将 npm 包放到 Go 项目根目录并使用本地模块替换。
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @error-reporting/go
|
|
7
|
+
go mod edit '-require=gitee.com/qglove/error-reporting-platform/packages/native/go@v0.1.0'
|
|
8
|
+
go mod edit '-replace=gitee.com/qglove/error-reporting-platform/packages/native/go=./node_modules/@error-reporting/go'
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```go
|
|
12
|
+
import sdk "gitee.com/qglove/error-reporting-platform/packages/native/go"
|
|
13
|
+
|
|
14
|
+
// 在应用入口调用一次,dsn 从工作台的接入配置复制。
|
|
15
|
+
if err := sdk.Init(sdk.Options{DSN: dsn, Environment: "production", Release: "git-sha"}); err != nil {
|
|
16
|
+
return err
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 在已有的错误处理分支补报。
|
|
20
|
+
sdk.CaptureException(err, sdk.CaptureContext{RequestID: "request-42"})
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`Init()` 也可从 `ERROR_REPORTING_DSN`、`ERROR_REPORTING_ENVIRONMENT` 和 `ERROR_REPORTING_RELEASE` 读取配置。
|
|
24
|
+
`CaptureException` 同步发送,成功返回事件 ID,失败返回空字符串。普通 Go `error` 的堆栈从调用点采集。
|
|
25
|
+
若要上报未处理的 panic,在需要监控的 goroutine 入口使用 `defer sdk.Recover()`,上报后仍按原流程 panic。
|
package/go.mod
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@error-reporting/go",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Error Reporting Platform SDK for Go",
|
|
5
|
+
"files": [
|
|
6
|
+
"go.mod",
|
|
7
|
+
"sdk.go"
|
|
8
|
+
],
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public",
|
|
11
|
+
"registry": "https://registry.npmjs.org/"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://gitee.com/qglove/error-reporting-platform.git",
|
|
16
|
+
"directory": "packages/native/go"
|
|
17
|
+
}
|
|
18
|
+
}
|
package/sdk.go
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Package errorreporting sends Go errors to the Error Reporting Platform.
|
|
2
|
+
package errorreporting
|
|
3
|
+
|
|
4
|
+
import (
|
|
5
|
+
"bytes"
|
|
6
|
+
"crypto/rand"
|
|
7
|
+
"encoding/hex"
|
|
8
|
+
"encoding/json"
|
|
9
|
+
"fmt"
|
|
10
|
+
"net/http"
|
|
11
|
+
"net/url"
|
|
12
|
+
"os"
|
|
13
|
+
"regexp"
|
|
14
|
+
"runtime"
|
|
15
|
+
"strings"
|
|
16
|
+
"sync/atomic"
|
|
17
|
+
"time"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
// Options holds the DSN and release metadata used for every event.
|
|
21
|
+
type Options struct {
|
|
22
|
+
DSN string
|
|
23
|
+
Environment string
|
|
24
|
+
Release string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// CaptureContext holds metadata for one event.
|
|
28
|
+
type CaptureContext struct{ RequestID string }
|
|
29
|
+
|
|
30
|
+
type config struct {
|
|
31
|
+
endpoint, key, environment, release string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
var current atomic.Pointer[config]
|
|
35
|
+
var projectPath = regexp.MustCompile(`^/[0-9]{1,24}/?$`)
|
|
36
|
+
var publicKey = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
|
|
37
|
+
var client = &http.Client{
|
|
38
|
+
Timeout: 2 * time.Second,
|
|
39
|
+
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Init configures the SDK once. Empty fields use the ERROR_REPORTING_* environment variables.
|
|
43
|
+
func Init(options ...Options) error {
|
|
44
|
+
opt := Options{}
|
|
45
|
+
if len(options) > 1 {
|
|
46
|
+
return fmt.Errorf("Init accepts one Options value")
|
|
47
|
+
}
|
|
48
|
+
if len(options) == 1 {
|
|
49
|
+
opt = options[0]
|
|
50
|
+
}
|
|
51
|
+
dsn, err := url.Parse(strings.TrimSpace(first(opt.DSN, os.Getenv("ERROR_REPORTING_DSN"))))
|
|
52
|
+
if err != nil || (dsn.Scheme != "http" && dsn.Scheme != "https") || dsn.Hostname() == "" ||
|
|
53
|
+
dsn.User == nil || !publicKey.MatchString(dsn.User.Username()) || !projectPath.MatchString(dsn.EscapedPath()) ||
|
|
54
|
+
dsn.ForceQuery || dsn.RawQuery != "" || dsn.Fragment != "" {
|
|
55
|
+
return fmt.Errorf("invalid error reporting DSN")
|
|
56
|
+
}
|
|
57
|
+
if _, present := dsn.User.Password(); present {
|
|
58
|
+
return fmt.Errorf("invalid error reporting DSN")
|
|
59
|
+
}
|
|
60
|
+
endpoint := &url.URL{Scheme: dsn.Scheme, Host: dsn.Host, Path: "/api/" + strings.Trim(dsn.Path, "/") + "/envelope/"}
|
|
61
|
+
cfg := &config{endpoint.String(), dsn.User.Username(),
|
|
62
|
+
first(opt.Environment, os.Getenv("ERROR_REPORTING_ENVIRONMENT"), "development"),
|
|
63
|
+
first(opt.Release, os.Getenv("ERROR_REPORTING_RELEASE"))}
|
|
64
|
+
if !current.CompareAndSwap(nil, cfg) {
|
|
65
|
+
return fmt.Errorf("error reporting is already initialized")
|
|
66
|
+
}
|
|
67
|
+
return nil
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// CaptureException sends a handled error and returns its event ID, or an empty string on failure.
|
|
71
|
+
func CaptureException(err error, context ...CaptureContext) string {
|
|
72
|
+
cfg := current.Load()
|
|
73
|
+
if cfg == nil || err == nil {
|
|
74
|
+
return ""
|
|
75
|
+
}
|
|
76
|
+
var idBytes [16]byte
|
|
77
|
+
if _, err := rand.Read(idBytes[:]); err != nil {
|
|
78
|
+
return ""
|
|
79
|
+
}
|
|
80
|
+
id := hex.EncodeToString(idBytes[:])
|
|
81
|
+
pcs := make([]uintptr, 50)
|
|
82
|
+
frames := runtime.CallersFrames(pcs[:runtime.Callers(2, pcs)])
|
|
83
|
+
stack := make([]map[string]any, 0, len(pcs))
|
|
84
|
+
for {
|
|
85
|
+
frame, more := frames.Next()
|
|
86
|
+
if frame.Function != "" {
|
|
87
|
+
stack = append(stack, map[string]any{"filename": clip(frame.File, 500), "function": clip(frame.Function, 180), "lineno": frame.Line})
|
|
88
|
+
}
|
|
89
|
+
if !more {
|
|
90
|
+
break
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for left, right := 0, len(stack)-1; left < right; left, right = left+1, right-1 {
|
|
94
|
+
stack[left], stack[right] = stack[right], stack[left]
|
|
95
|
+
}
|
|
96
|
+
tags := map[string]string{}
|
|
97
|
+
if len(context) > 0 && context[0].RequestID != "" {
|
|
98
|
+
tags["request_id"] = clip(context[0].RequestID, 128)
|
|
99
|
+
}
|
|
100
|
+
event := map[string]any{
|
|
101
|
+
"event_id": id, "timestamp": time.Now().UTC().Format(time.RFC3339Nano), "platform": "go",
|
|
102
|
+
"environment": clip(cfg.environment, 80), "release": clip(cfg.release, 160), "tags": tags,
|
|
103
|
+
"exception": map[string]any{"values": []any{map[string]any{
|
|
104
|
+
"type": clip(fmt.Sprintf("%T", err), 120), "value": clip(err.Error(), 2000),
|
|
105
|
+
"stacktrace": map[string]any{"frames": stack},
|
|
106
|
+
}}},
|
|
107
|
+
}
|
|
108
|
+
var envelope bytes.Buffer
|
|
109
|
+
enc := json.NewEncoder(&envelope)
|
|
110
|
+
for _, part := range []any{map[string]string{"event_id": id}, map[string]string{"type": "event"}, event} {
|
|
111
|
+
if enc.Encode(part) != nil {
|
|
112
|
+
return ""
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
req, err := http.NewRequest(http.MethodPost, cfg.endpoint, &envelope)
|
|
116
|
+
if err != nil {
|
|
117
|
+
return ""
|
|
118
|
+
}
|
|
119
|
+
req.Header.Set("Content-Type", "application/x-sentry-envelope")
|
|
120
|
+
req.Header.Set("X-Sentry-Auth", "Sentry sentry_version=7, sentry_key="+cfg.key)
|
|
121
|
+
res, err := client.Do(req)
|
|
122
|
+
if err != nil {
|
|
123
|
+
return ""
|
|
124
|
+
}
|
|
125
|
+
defer res.Body.Close()
|
|
126
|
+
if res.StatusCode < 200 || res.StatusCode >= 300 {
|
|
127
|
+
return ""
|
|
128
|
+
}
|
|
129
|
+
return id
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Recover reports a panic when directly deferred in its goroutine, then re-panics.
|
|
133
|
+
func Recover() {
|
|
134
|
+
if value := recover(); value != nil {
|
|
135
|
+
if err, ok := value.(error); ok {
|
|
136
|
+
CaptureException(err)
|
|
137
|
+
} else {
|
|
138
|
+
CaptureException(fmt.Errorf("%v", value))
|
|
139
|
+
}
|
|
140
|
+
panic(value)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// first returns the first configured value.
|
|
145
|
+
func first(values ...string) string {
|
|
146
|
+
for _, value := range values {
|
|
147
|
+
if value != "" {
|
|
148
|
+
return value
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return ""
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// clip limits the amount of diagnostic text in the envelope.
|
|
155
|
+
func clip(value string, limit int) string {
|
|
156
|
+
for index := range value {
|
|
157
|
+
if limit == 0 {
|
|
158
|
+
return value[:index]
|
|
159
|
+
}
|
|
160
|
+
limit--
|
|
161
|
+
}
|
|
162
|
+
return value
|
|
163
|
+
}
|