本文介绍通过 pgx库集成sentry, pgx 特点是速度快,可以完全控制,并且支持所有 postgres 数据类型。
pgx地址: https://github.com/jackc/pgx
最简单的接入方式是自定义一个logger, 然后注入到pgx, 完整示例如下
go
package main
import (
"context"
"log"
"os"
"time"
"github.com/getsentry/sentry-go"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/log/logrusadapter"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/sirupsen/logrus"
)
// TracingLogger does two things at once, logging and tracing
type TracingLogger struct {
logger *logrusadapter.Logger
}
func NewTracingLogger(logger logrus.FieldLogger) *TracingLogger {
return &TracingLogger{logger: logrusadapter.NewLogger(logger)}
}
func (l *TracingLogger) Log(ctx context.Context, level pgx.LogLevel, msg string, data map[string]interface{}) {
l.logger.Log(ctx, level, msg, data)
span := sentry.StartSpan(ctx, "postgres "+msg)
defer span.Finish()
if data != nil {
if span.Data == nil {
span.Data = make(map[string]interface{})
}
for key, value := range data {
value, ok := value.(string)
if ok {
span.Data[key] = value
}
}
// since this method is called after a query is done,
// we need to correct span start time
execTime, ok := data["time"].(time.Duration)
if ok {
span.StartTime = time.Now().Add(-execTime)
}
}
}
func main() {
err := sentry.Init(sentry.ClientOptions{
Debug: true,
Dsn: "https://a5eac4fa3396cbfac8fb4baa6a9c03a3@o4504291071688704.ingest.sentry.io/4506715873804288",
AttachStacktrace: true,
EnableTracing: true,
SampleRate: 1.0,
TracesSampleRate: 1.0,
ProfilesSampleRate: 1.0,
})
if err != nil {
log.Fatalf("sentry.Init: %s", err)
}
defer sentry.Flush(2 * time.Second)
config, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
logger := logrus.New()
config.ConnConfig.Logger = NewTracingLogger(logger)
conn, err := pgxpool.ConnectConfig(ctx, config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ctx := context.Background()
tx := sentry.StartTransaction(ctx, "test_pgx")
defer tx.Finish()
ctx = tx.Context()
err = conn.QueryRow(ctx, "SELECT 1").Scan()
if err != nil {
log.Fatal(err)
}
}
参考: