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/

相关推荐
码一行21 小时前
Eino AI 实战:解析 PDF 文件 & 实现 MCP Server
后端·go
赵大海2 天前
golang运维平台实战,服务树,日志监控,任务执行,分布式探测
go
喵个咪2 天前
go-kratos-admin 快速上手指南:从环境搭建到启动服务(Windows/macOS/Linux 通用)
vue.js·go
码一行2 天前
Eino AI 实战: Eino 的文档加载与解析
后端·go
码一行2 天前
Eino AI 实战:DuckDuckGo 搜索工具 V1 与 V2
后端·go
代码扳手2 天前
Golang 高效内网文件传输实战:零拷贝、断点续传与 Protobuf 指令解析(含完整源码)
后端·go
zhuyasen2 天前
Go Web 开发利器:如何让你的 Gin 服务拥有 Nginx 般的静态文件处理能力?
nginx·go·gin
爷_2 天前
Golang: sqlc 和 goose 最佳实践
后端·go·全栈
喵个咪2 天前
go-kratos-admin 技术栈深度解析:为什么选 Golang+Vue3 这套组合?
vue.js·go
码一行3 天前
Go.1.25.4 和 Go.1.24.10 发布了!!
后端·go