0%

sentry监控与golang的使用

Sentry 是一个开源的非常强大的实时异常收集系统,可以为开发者的提供帮助、诊断,修复和优化其代码的性能的能力,可以用它来监控线上服务的健康状态,实时收集的异常堆栈信息可以帮助我们快速发现、定位和修复问题。

1. 安装使用

1.1 安装

1
2
3
git clone https://github.com/getsentry/self-hosted sentry
sudo ./install.sh
sudo docker-compose up -d
image-20220727112838445
  • 报错

    ▶ Detecting Docker platform
    panic: reflect: indirection through nil pointer to embedded struct [recovered]

    1
    2
    3
    4
    # 确认下docker和docker-compose版本是否满足
    sudo curl -L https://github.com/docker/compose/releases/download/v2.7.0/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose

    sudo chmod +x /usr/local/bin/docker-compose

1.2 创建项目

  • 访问9000端口,创建用户,这时候一定要放开注册。

    • create project
    • Go 项目

1.3 配置邮箱

1
2
3
4
sudo docker-compose down
sudo docker-compose build --force-rm
sudo docker-compose run --rm web upgrade
sudo docker-compose up -d

进入页面,在左上角的你的昵称位置单击,选择Admin。

然后在左侧选择Mail,然后在最下面有一个测试设置。点击“向送一封测试邮件”。如果收到的话,那么说明就配置成功了。

2. 代码

2.1 添加中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import	sentrygin "github.com/getsentry/sentry-go/gin"

appEngine.Use(sentrygin.New(sentrygin.Options{}))
appEngine.Use(sentry.CaptureSentryMiddleware)



func Init() {
//TODO: DSN 配置
err := sentry.Init(sentry.ClientOptions{
Dsn: "http://1ccf51b1319f49c48e95cb56b7dc8fc4@192.168.40.98:9000/2",
// Set TracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production,
TracesSampleRate: 1.0,
})
if err != nil {
lqlog.Info("sentry init err:%v", err)
return
}
return
}

2.2 上报

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
package sentry

import (
"bytes"
"encoding/json"

"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-gonic/gin"
)

type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}

func CaptureSentryMiddleware(ctx *gin.Context) {
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer}
ctx.Writer = blw

hub := sentrygin.GetHubFromContext(ctx)
if hub == nil {
return
}
hub.Scope().SetRequest(ctx.Request)

ctx.Next()

statusCode := ctx.Writer.Status()
if statusCode >= 400 {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("code", statusCode)
hub.CaptureMessage(blw.body.String())
})

} else if statusCode == 200 {
resp := struct {
ErrCode int64 `json:"errCode"`
ErrMsg string `json:"errMsg"`
ErrMsgDesc string `json:"errMsgDesc"`
}{}
_ = json.Unmarshal([]byte(blw.body.String()), &resp)
if resp.ErrCode != 0 {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("resp", blw.body.String())
hub.CaptureMessage(ctx.Request.RequestURI)
})
}
}
}

3. 参考资料

给作者打赏,可以加首页微信,咨询作者相关问题!