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/

相关推荐
于顾而言16 小时前
【笔记】Go Coding In Go Way
后端·go
qq_1728055916 小时前
GIN 反向代理功能
后端·golang·go
follycat1 天前
2024强网杯Proxy
网络·学习·网络安全·go
OT.Ter1 天前
【力扣打卡系列】单调栈
算法·leetcode·职场和发展·go·单调栈
探索云原生1 天前
GPU 环境搭建指南:如何在裸机、Docker、K8s 等环境中使用 GPU
ai·云原生·kubernetes·go·gpu
OT.Ter1 天前
【力扣打卡系列】移动零(双指针)
算法·leetcode·职场和发展·go
码财小子2 天前
k8s 集群中 Golang pprof 工具的使用
后端·kubernetes·go
明月看潮生5 天前
青少年编程与数学 02-003 Go语言网络编程 04课题、TCP/IP协议
青少年编程·go·网络编程·编程与数学
明月看潮生6 天前
青少年编程与数学 02-003 Go语言网络编程 03课题、网络编程协议
青少年编程·go·网络编程·编程与数学
帅气的人1236 天前
thrift idl 语言基础学习
java·开发语言·python·rpc·go·thrfit