github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/log/sentry.go (about) 1 package log 2 3 import ( 4 "context" 5 "fmt" 6 "runtime/debug" 7 "strings" 8 "time" 9 10 "github.com/cockroachdb/errors" 11 "github.com/getsentry/sentry-go" 12 "github.com/projecteru2/core/types" 13 "google.golang.org/grpc/peer" 14 ) 15 16 // SentryDefer . 17 func SentryDefer() { 18 if sentryDSN == "" { 19 return 20 } 21 defer sentry.Flush(2 * time.Second) 22 if r := recover(); r != nil { 23 sentry.CaptureMessage(fmt.Sprintf("%+v: %s", r, debug.Stack())) 24 panic(r) 25 } 26 } 27 28 func genGRPCTracingInfo(ctx context.Context) (tracingInfo string) { 29 if ctx == nil { 30 return "" 31 } 32 33 tracing := []string{} 34 if p, ok := peer.FromContext(ctx); ok { 35 tracing = append(tracing, p.Addr.String()) 36 } 37 38 if traceID := ctx.Value(types.TracingID); traceID != nil { 39 if tid, ok := traceID.(string); ok { 40 tracing = append(tracing, tid) 41 } 42 } 43 tracingInfo = strings.Join(tracing, "-") 44 return 45 } 46 47 func reportToSentry(ctx context.Context, level sentry.Level, err error, format string, args ...any) { //nolint 48 if sentryDSN == "" { 49 return 50 } 51 defer sentry.Flush(2 * time.Second) 52 event, extraDetails := errors.BuildSentryReport(err) 53 for k, v := range extraDetails { 54 event.Extra[k] = v 55 } 56 event.Level = level 57 58 if msg := fmt.Sprintf(format, args...); msg != "" { 59 event.Tags["message"] = msg 60 } 61 62 if tracingInfo := genGRPCTracingInfo(ctx); tracingInfo != "" { 63 event.Tags["tracing"] = tracingInfo 64 } 65 66 if res := string(*sentry.CaptureEvent(event)); res != "" { 67 WithFunc("log.reportToSentry").WithField("ID", res).Info(ctx, "Report to Sentry") 68 } 69 }