grpc服務如何新增sentry監控(新增中介軟體)
阿新 • • 發佈:2020-09-16
[toc]
# 需求
sentry是一款非常好用的工具,可以方便追蹤線上的異常,在gin框架裡邊可以使用Use新增中件間,但是grpc服務在網上搜索了一堆沒一個能用的,只能硬著頭皮看原始碼
終於搞定!
grpc服務有一個github.com/grpc-ecosystem/go-grpc-middleware的中介軟體外掛,可以新增多個外掛,使用如下,其實就是住裡邊追加中介軟體
![](https://img2020.cnblogs.com/blog/662544/202009/662544-20200916115311318-884397435.png)
![](https://img2020.cnblogs.com/blog/662544/202009/662544-20200916115208528-1305770648.png)
分別是捕獲正常方法和流式方法的請求
我們看看中介軟體的定義
```golang
type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)
```
我們只需要寫一個類似的中介軟體就行了,talk is cheap,上程式碼!
# 解決
新增中介軟體
```
package middleware
import (
"errors"
"fmt"
"github.com/getsentry/sentry-go"
"golang.org/x/net/context"
"google.golang.org/grpc"
"time"
)
func SentryUnaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
defer func() {
if r := recover(); r != nil {
flushToSentry(r)
}
}()
return handler(ctx, req)
}
}
func SentryStreamServerInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
defer func() {
if r := recover(); r != nil {
flushToSentry(r)
}
}()
return handler(srv, stream)
}
}
func flushToSentry(v interface{}) {
sentry.CaptureException(errors.New(fmt.Sprintf("%v", v)))
sentry.Flush(time.Second * 5)
}
```
將上面的中介軟體註冊
![](https://img2020.cnblogs.com/blog/662544/202009/662544-20200916115509780-707012594.png)
再來找個程式碼試一試,這裡我顯式拋了一個異常`chenqionghe test`
![](https://img2020.cnblogs.com/blog/662544/202009/662544-20200916115606410-995941243.png)
呼叫後,發現sentry已經能正常收集到異常,如下
![](https://img2020.cnblogs.com/blog/662544/202009/662544-20200916115728900-803143285.png)
就是這麼簡單