opentracing integration with GORM

gorm-opentracing

Go Report Card go.dev reference

opentracing support for gorm2.

Features

  • Record SQL in span logs.
  • Record Result in span logs.
  • Record Table in span tags.
  • Record Error in span tags and logs.
  • Register Create Query Delete Update Row Raw tracing callbacks.

Get Started

I assume that you already have an opentracing Tracer client started in your project.

func main() {
	var db *gorm.DB
	
	db.Use(gormopentracing.New())
}

Otherwise, you need to deploy distributed tracing server(jaeger, zipkin for example), then you need to boot tracer client in yours project and set tracer to opentracing.

import (
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	"github.com/uber/jaeger-client-go/config"
	jaegerlog "github.com/uber/jaeger-client-go/log"
)

func bootTracerBasedJaeger() {
	// jaeger tracer configuration
	cfg := &config.Configuration{
		Sampler: &config.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1,
		},
		ServiceName: "gormopentracing",
		Reporter: &config.ReporterConfig{
			LogSpans: true,
			//LocalAgentHostPort:  "127.0.0.1:6381",
			BufferFlushInterval: 100 * time.Millisecond,
			CollectorEndpoint:   "http://127.0.0.1:14268/api/traces",
		},
	}

	// jaeger tracer client 
	tracer, _, err := cfg.NewTracer(
		config.Logger(jaegerlog.StdLogger),
		config.ZipkinSharedRPCSpan(true),
	)
	if err != nil {
		log.Printf("failed to use jaeger tracer plugin, got error %v", err)
		os.Exit(1)
	}
	
	// set into opentracing
	opentracing.SetGlobalTracer(tracer)
}

Plugin options

// WithLogResult log result into span log, default: disabled.
func WithLogResult(logResult bool)

Snapshots

Comments
  • Ability tagging span as error for specific errors

    Ability tagging span as error for specific errors

    Hi.

    Thanks for the great lib.

    I wanted to ask: This lib add error tag on span on every error, even for ErrRecordNotFound. But ErrRecordNotFound it's not an error (from my point of view).

    Maybe need to add Option which will allow to skip error tagging for some errors?

    image

  • And project support pass a tracker?

    And project support pass a tracker?

    Describe the feature

    Pass a tracker instead of global one

    Motivation

    I want use other ServiceName of tracker like "mysql" "postgres"

  • How to use it? Are there  complete examples?

    How to use it? Are there complete examples?

    func main() {
    	bootTracerBasedJaeger()
    
    	db, _ := gorm.Open(mysql.Open("DSN"))
    
    	db.Use(gormopentracing.New())
    
    	span := opentracing.StartSpan("gorm")
    	defer span.Finish()
    
    	ctx := opentracing.ContextWithSpan(context.Background(), span)
    
    	sess := db.WithContext(ctx)
    
    	account := &Account{}
    
    	sess.First(&account, 1)
    }
    

    // Reporting span 35bb47763bfe8a72:35bb47763bfe8a72:0000000000000000:1

    But nothing can be searched in jaeger UI.

  • Add operation name options

    Add operation name options

    • [x] Do only one thing
    • [x] Non breaking API changes
    • [x] Tested

    What did this pull request do?

    Adds options for operation names:

    • WithCreateOpName
    • WithUpdateOpName
    • WithQueryOpName
    • WithDeleteOpName
    • WithRowOpName
    • WithRawOpName
  • feat: support customized tracer

    feat: support customized tracer

    • [x] Do only one thing
    • [x] Nonbreaking API changes
    • [x] Tested

    What did this pull request do?

    • provide the WithTracer API to customize tracer
    • use opt options instead of logResult and tracer property in opentracingPlugin
    • define extractAfter and injectBefore into opentracingPlugin methods, and rename helper.go as opentracing_helper.go

    User Case Description

    use customized tracer of DB operation rather than have to use global tracer.

  • export applyOptions

    export applyOptions

    • [x] Do only one thing
    • [x] Non breaking API changes
    • [x] Tested

    What did this pull request do?

    Exports applyOptions for consumption by applications. This is potentially useful for building a conditional/dynamic list of options, without having to call gormopentracing.New() in each of the conditionals. For example:

    if condition {
          gormopentracing.New(
              gormopentracing.WithTracer(tracer),
              gormopentracing.WithSqlParameters(false),
              )
    } else
          gormopentracing.New(
              gormopentracing.WithTracer(tracer),
              gormopentracing.WithSqlParameters(true),
              )
    }
    

    Becomes:

    if condition {
              applyOpts := []gormopentracing.ApplyOpts {
                  gormopentracing.WithTracer(tracer),
                  gormopentracing.WithSqlParameters(false),
                  // other opts
              }
    } else
              applyOpts := []gormopentracing.ApplyOpts {
                  gormopentracing.WithTracer(),
                  gormopentracing.WithSqlParameters(true),
                  // other opts
              }
    }
    gormopentracing.New(...applyOpts)
    
  • feat: Conditionally log sql query parameters

    feat: Conditionally log sql query parameters

    • [X] Do only one thing
    • [X] Non breaking API changes
    • [X] Tested

    What did this pull request do?

    This change adds flag that conditionally adds parameters to sql queries.

    User Case Description

    I don't want to expose sensitive data from sql queries to jeager through traces. That's why adding this flag would be really helpful to keep sql statements with placeholders instead of variables.

  • docs: update readme

    docs: update readme

    • [x] Do only one thing
    • [x] Non breaking API changes
    • [x] Tested

    What did this pull request do?

    update readme

    User Case Description

    describes how to specify the tracer to the opentracing plugin

Related tags
100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.

go-queryset 100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood. Contents

Dec 30, 2022
A code generator base on GORM

GORM/GEN The code generator base on GORM, aims to be developer friendly. Overview CRUD or DIY query method code generation Auto migration from databas

Jan 1, 2023
Converts a database into gorm structs and RESTful api

gen The gen tool produces a CRUD (Create, read, update and delete) REST api project template from a given database. The gen tool will connect to the d

Dec 28, 2022
Scope function for GORM queries provides easy filtering with query parameters

Gin GORM filter Scope function for GORM queries provides easy filtering with query parameters Usage go get github.com/ActiveChooN/gin-gorm-filter Mod

Dec 28, 2022
A plugin to allow telemetry by NewRelic Go Agent for GORM

GORM NewRelic Telemetry Plugin A plugin to allow telemetry by NewRelic Go Agent for GORM Overview Plugin implementation to add datastore segments on a

Aug 19, 2022
Gorm firebird driver

gorm-firebird GORM firebird driver import: "github.com/flylink888/gorm-firebird" Example: var products []Product dsn := "SYSDBA:[email protected]/sy

Sep 27, 2022
OpenTelemetry plugin for GORM v2

gorm-opentelemetry OpenTelemetry plugin for GORM v2 Traces all queries along with the query SQL. Usage Example: // Copyright The OpenTelemetry Authors

Jan 11, 2022
CURD using go fiber - gorm - mysql

GO Fiber - CRUD - GORM - Mysql Folder Structure - database | database config |- migration | migration config - middleware | mid

Nov 13, 2022
A example of a join table using liquibase and gorm

A example of a join table using liquibase and gorm. Additionally the join table's composite key is used as a composite foreign key for another table.

Feb 4, 2022
Fiber Clean Architecture With GORM

Fiber Clean Architecture With GORM I offer this repository as a proposal for a c

Oct 30, 2022
Ormtool - 将数据库表转换为golang的结构体,自定义生成tag,如json,gorm,xorm和简单的db信息

数据库表转换为golang 结构体 1. 获取方式 2. 配置说明 # 保存路径 SavePath: "./models/test.go", # 是

May 30, 2022
Simple-crm-system - Simple CRM system CRUD backend using Go, Fiber, SQLite, Gorm

Simple CRM system CRUD backend using GO, Fiber, Gorm, SQLite Developent go mod t

Nov 13, 2022
Api-project - Api project with Golang, Gorm, Gorilla-Mux, Postgresql

TECHNOLOGIES GOLANG 1.14 GORM GORILLA-MUX POSTGRESQL API's PATHS For Product Ser

Nov 23, 2022
This library is a complementary library for Gorm (v2) which resolves the first available pool passed to it.

This library is a complementary library for Gorm (v2) which resolves the first available pool passed to it.

Feb 2, 2022
EZCoin is a control panel for Bitfinex funding, backend is build by Golang, Gin and GORM, frontend is build by angular

EZCoin server is backend for Bitfinex funding, it build by Golang, Gin and GORM.

Feb 7, 2022
RestAPI Starter Template Using Go (Gin + Gorm)

go-gin-gorm-restapi-template Go (Gin + Gorm) を使用した RestAPI 開発のスターターテンプレート RestAPI Starter Template Using Golang (Gin + Gorm) 主要な依存ライブラリ Gin (Web フレームワ

Apr 3, 2022
A simple CRUD API made with Go, Postgres, FIber, Gorm and Docker.

golang-test-api A simple CRUD API made with Go, Postgres, FIber, Gorm and Docker. Cloning the repository To clone the repository run the following com

Dec 14, 2022
Opentracing factory to setup by multiples vendors

telemetry Opentracing factory to setup by multiples vendors. Usage telemetry.InitTracer( telemetry.WithJaeger(os.Getenv("APP_NAME")), telemetr

Jul 23, 2021
The plugins of opentracing-go.

OpenTracing-Go-Plugins The plugins of opentracing-go. Installation go get -u github.com/yuewokeji/opentracing-go-plugins Configuration Initialize a tr

May 3, 2022
Progress OpenEdge Profiler data parsing to OpenTracing format

openedge-profiler-parser Progress OpenEdge Profiler data parsing to OpenTracing format. Prerequisites In order to RUN you will be enough with Docker:

Nov 9, 2021