otelsql

package module
v2.0.0-...-341fd6f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2022 License: Apache-2.0 Imports: 22 Imported by: 0

README

otelsql

Fork https://github.com/nhatthm/otelsql Also good to know - https://github.com/XSAM/otelsql

How to use

IMPORTANT: You should always use context base commands and pass ...

sql driver.Connector

note: connection address format 127.0.0.1:9000

example: ./example/clickhouse where layer of db implementation: ./example/clickhouse/pkg/db/connector

package connector

func main() {
	//...
	var conector = getConnectorForYourDriver()

	//// wrap module
	dbc := otelsql.WrapConnector(conector,
		otelsql.WithMeterProvider(tel.FromCtx(ctx).MetricProvider()),
		otelsql.AllowRoot(),
		otelsql.WithInstanceName(tel.GetConfigFromEnv().Namespace),
		otelsql.DisableErrSkip(),
		otelsql.TraceQueryWithoutArgs(),
		otelsql.TraceRowsClose(),
		otelsql.TraceRowsAffected(),
		otelsql.WithTracerProvider(tel.FromCtx(ctx).TracerProvider()),
	)

	// create connection with sql.OpenDB
	db := sql.OpenDB(dbc)
	db.SetMaxIdleConns(5)
	db.SetMaxOpenConns(10)
	db.SetConnMaxLifetime(time.Hour)

	if err := db.Ping(); err != nil {
		tel.FromCtx(ctx).Panic("db ping", tel.Error(err))
	}

	// begin collect metrics
	if err := otelsql.RecordStats(db); err != nil {
		tel.FromCtx(ctx).Panic("otelsql RecordStats", tel.Error(err))
	}

	//...
}

sql

example: ./example/clickhouse where layer of db implementation: ./example/clickhouse/pkg/db/open

package open

import (
	"database/sql"
	_ "github.com/ClickHouse/clickhouse-go/v2"
	otelsql "github.com/d7561985/tel/plugins/otelsql/v2"
	"github.com/pkg/errors"
	semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
	"time"
)

func open() (*sql.DB, error) {
	// Register the otelsql wrapper for the provided postgres driver.
	driverName, err := otelsql.Register("clickhouse",
		otelsql.AllowRoot(),
		otelsql.TraceQueryWithoutArgs(),
		otelsql.TraceRowsClose(),
		otelsql.TraceRowsAffected(),
		otelsql.WithDatabaseName("my_database"),        // Optional.
		otelsql.WithSystem(semconv.DBSystemPostgreSQL), // Optional.
	)
	if err != nil {
		return nil, err
	}

	// Connect to a Clickhouse database using the postgres driver wrapper.
	// create connection with sql.OpenDB
	db, err := sql.Open(driverName, dsn)
	if err != nil {
		return nil, errors.WithMessagef(err, "open")
	}

	db.SetMaxIdleConns(5)
	db.SetMaxOpenConns(10)
	db.SetConnMaxLifetime(time.Hour)

	if err = db.Ping(); err != nil {
		return nil, errors.WithMessagef(err, "ping")
	}

	return db, nil
}

Documentation

Overview

Package otelsql provides traces and metrics for database/sql drivers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContextWithQuery

func ContextWithQuery(ctx context.Context, query string) context.Context

ContextWithQuery attaches the query to the parent context.

func QueryFromContext

func QueryFromContext(ctx context.Context) string

QueryFromContext gets the query from context.

func RecordStats

func RecordStats(db *sql.DB, opts ...StatsOption) error

RecordStats records database statistics for provided sql.DB at the provided interval.

func Register

func Register(driverName string, options ...DriverOption) (string, error)

Register initializes and registers our otelsql wrapped database driver identified by its driverName and using provided options. On success, it returns the generated driverName to use when calling sql.Open.

It is possible to register multiple wrappers for the same database driver if needing different options for different connections.

func RegisterWithSource

func RegisterWithSource(driverName string, source string, options ...DriverOption) (string, error)

RegisterWithSource initializes and registers our otelsql wrapped database driver identified by its driverName, using provided options.

source is useful if some drivers do not accept the empty string when opening the DB. On success, it returns the generated driverName to use when calling sql.Open.

It is possible to register multiple wrappers for the same database driver if needing different options for different connections.

func SemVersion

func SemVersion() string

SemVersion is the semantic version to be supplied to tracer/meter creation.

func Version

func Version() string

Version is the current release version of the otelsql instrumentation.

func Wrap

func Wrap(d driver.Driver, opts ...DriverOption) driver.Driver

Wrap takes a SQL driver and wraps it with OpenTelemetry instrumentation.

func WrapConnector

func WrapConnector(dc driver.Connector, opts ...DriverOption) driver.Connector

WrapConnector allows wrapping a database driver.Connector which eliminates the need to register ocsql as an available driver.Driver.

Types

type DriverOption

type DriverOption interface {
	// contains filtered or unexported methods
}

DriverOption allows for managing otelsql configuration using functional options.

func AllowRoot

func AllowRoot() DriverOption

AllowRoot allows otelsql to create root spans in absence of existing spans or even context.

Default is to not trace otelsql calls if no existing parent span is found in context or when using methods not taking context.

func ConvertErrorToSpanStatus

func ConvertErrorToSpanStatus(f errorToSpanStatus) DriverOption

ConvertErrorToSpanStatus sets a custom error converter.

func DisableErrSkip

func DisableErrSkip() DriverOption

DisableErrSkip suppresses driver.ErrSkip errors in spans if set to true.

func TraceAll

func TraceAll() DriverOption

TraceAll enables the creation of spans on methods.

func TraceLastInsertID

func TraceLastInsertID() DriverOption

TraceLastInsertID enables the creation of spans on LastInsertId calls.

func TracePing

func TracePing() DriverOption

TracePing enables the creation of spans on Ping requests.

func TraceQuery

func TraceQuery(f queryTracer) DriverOption

TraceQuery sets a custom function that will return a list of attributes to add to the spans with a given query and args.

For example:

otelsql.TraceQuery(func(sql string, args []driver.NamedValue) []attribute.KeyValue {
	attrs := make([]attribute.KeyValue, 0)
	attrs = append(attrs, semconv.DBStatementKey.String(sql))

	for _, arg := range args {
		if arg.Name != "password" {
			attrs = append(attrs, sqlattribute.FromNamedValue(arg))
		}
	}

	return attrs
})

func TraceQueryWithArgs

func TraceQueryWithArgs() DriverOption

TraceQueryWithArgs will add to the spans the given sql query and all arguments.

func TraceQueryWithoutArgs

func TraceQueryWithoutArgs() DriverOption

TraceQueryWithoutArgs will add to the spans the given sql query without any arguments.

func TraceRowsAffected

func TraceRowsAffected() DriverOption

TraceRowsAffected enables the creation of spans on RowsAffected calls.

func TraceRowsClose

func TraceRowsClose() DriverOption

TraceRowsClose enables the creation of spans on RowsClose calls.

func TraceRowsNext

func TraceRowsNext() DriverOption

TraceRowsNext enables the creation of spans on RowsNext calls. This can result in many spans.

func WithSpanNameFormatter

func WithSpanNameFormatter(f spanNameFormatter) DriverOption

WithSpanNameFormatter sets tracer provider.

func WithTracerProvider

func WithTracerProvider(p trace.TracerProvider) DriverOption

WithTracerProvider sets tracer provider.

type Option

type Option interface {
	DriverOption
	StatsOption
}

Option allows for managing otelsql configuration using functional options.

func WithDatabaseName

func WithDatabaseName(system string) Option

WithDatabaseName sets database name.

func WithDefaultAttributes

func WithDefaultAttributes(attrs ...attribute.KeyValue) Option

WithDefaultAttributes will be set to each span as default.

func WithInstanceName

func WithInstanceName(instanceName string) Option

WithInstanceName sets database instance name.

func WithMeterProvider

func WithMeterProvider(p metric.MeterProvider) Option

WithMeterProvider sets meter provider.

func WithSystem

func WithSystem(system attribute.KeyValue) Option

WithSystem sets database system name. See: semconv.DBSystemKey.

type StatsOption

type StatsOption interface {
	// contains filtered or unexported methods
}

StatsOption allows for managing otelsql configuration using functional options.

func WithMinimumReadDBStatsInterval

func WithMinimumReadDBStatsInterval(interval time.Duration) StatsOption

WithMinimumReadDBStatsInterval sets the minimum interval between calls to db.Stats(). Negative values are ignored.

type TraceOptions

type TraceOptions struct {

	// AllowRoot, if set to true, will allow otelsql to create root spans in absence of existing spans or even context.
	//
	// Default is to not trace otelsql calls if no existing parent span is found in context or when using methods not taking context.
	AllowRoot bool

	// Ping, if set to true, will enable the creation of spans on Ping requests.
	Ping bool

	// RowsNext, if set to true, will enable the creation of spans on RowsNext calls. This can result in many spans.
	RowsNext bool

	// RowsClose, if set to true, will enable the creation of spans on RowsClose calls.
	RowsClose bool

	// RowsAffected, if set to true, will enable the creation of spans on RowsAffected calls.
	RowsAffected bool

	// LastInsertID, if set to true, will enable the creation of spans on LastInsertId calls.
	LastInsertID bool
	// contains filtered or unexported fields
}

TraceOptions are options to enable the creations of spans on sql calls.

Directories

Path Synopsis
Package attribute provides functionalities for converting database values to attributes.
Package attribute provides functionalities for converting database values to attributes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL