golang 集成sentry:PostgreSQL

本文介绍通过 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)
	}
}

参考:

https://anymindgroup.com/news/tech-blog/15724/

相关推荐
彭岳林4 小时前
nil是什么?
go
浮尘笔记4 小时前
go-zero使用elasticsearch踩坑记:时间存储和展示问题
大数据·elasticsearch·golang·go
彭岳林4 小时前
err != nil ?
go
杰克逊的黑豹4 小时前
不再迷茫:Rust, Zig, Go 和 C
c++·rust·go
DemonAvenger1 天前
深入剖析 sync.Once:实现原理、应用场景与实战经验
分布式·架构·go
一个热爱生活的普通人2 天前
Go语言中 Mutex 的实现原理
后端·go
孔令飞2 天前
关于 LLMOPS 的一些粗浅思考
人工智能·云原生·go
小戴同学2 天前
实时系统降低延时的利器
后端·性能优化·go
Golang菜鸟3 天前
golang中的组合多态
后端·go
Serverless社区3 天前
函数计算支持热门 MCP Server 一键部署
go