goopentelemetry

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2023 License: MIT Imports: 32 Imported by: 1

README

go-opentelemetry

Getting Started

You can find a getting started guide on opentelemetry.io.

OpenTelemetry's goal is to provide a single set of APIs to capture distributed traces and metrics from your application and send them to an observability platform. This project allows you to do just that for applications written in Go. There are two steps to this process: instrument your application, and configure an exporter.

Dependency

Install

Go Version 1.16+

go get github.com/erajayatech/go-opentelemetry

Setup Environment

  • Set the following environment variables:
  • MODE=<your_application_mode>
    • Example : prod
  • APP_VERSION=<your_application_version>
  • APP_NAME=<your_application_name>
  • OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317
  • OTEL_EXPORTER_OTLP_HEADERS="api-key=<your_license_key>"
  • OTEL_SAMPLED=true
    • Be careful about using this sampler in a production application with significant traffic: a new trace will be started and exported for every request. If you won't sampling for every request just set to false

How To Use

  • Import package on main.go
otel "github.com/erajayatech/go-opentelemetry"
  • Add below code to main.go
otelTracerService := otel.ConstructOtelTracer()
otelTracerServiceErr := otelTracerService.SetTraceProviderNewRelic(ctx)
if otelTracerServiceErr != nil {
    panic(otelTracerServiceErr)
}
  • Tracing Controller

    • Import package
    otel "github.com/erajayatech/go-opentelemetry"
    
    • Start Span Tracer
    ctx, span := otel.Start(context)
    defer span.End()
    
    • Use code below to add span's tags
    otel.AddSpanTags(span, map[string]string{"traceId": singleton.Trace().ID, "RegisterRequest": string(requestMarshalled)})
    
    • Use code below to add span error
    if err != nil {
        otel.AddSpanError(span, err)
        otel.FailSpan(span, "Request not valid")
        httpresponse.BadRequest(context, "Request not valid")
        return
    }
    
  • Tracing Service

    • Import package
    otel "github.com/erajayatech/go-opentelemetry"
    
    • Add context argument to function that we want to trace, example :
    func (service *RegisterService) Register(context context.Context, request RegisterRequest, platform string) *httpresponse.HTTPError {}
    
    • Use code below for add span
    ctx, span := otel.NewSpan(context, "authregister.service.Register", "")
    defer span.End()
    
    • Use code below to add span error
    if registeredPlatforms.Id == 0 {
        httpError.Code = http.StatusBadRequest
        httpError.Message = "Platform not valid"
        otel.AddSpanError(span, valErr)
        otel.FailSpan(span, httpError.Message)
        return &httpError
    }
    
  • Tracing Query

    • Add code below on database.go
      • Import package
      "gorm.io/gorm/logger"
      "gorm.io/plugin/opentelemetry/logging/logrus"
      "gorm.io/plugin/opentelemetry/tracing"
      
      • Set gorm logger
      logger := logger.New(
          logrus.NewWriter(),
          logger.Config{
              SlowThreshold: time.Millisecond,
              LogLevel:      logger.Warn,
              Colorful:      false,
          },
      )
      
      db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger})
      
      if err != nil {
          log.Println("Connected to database Failed:", err)
      }
      
      if err := db.Use(tracing.NewPlugin()); err != nil {
          panic(err)
      }
      
    • Add code below on repository
      • Import package
      otel "github.com/erajayatech/go-opentelemetry"
      
      • Add context argument to function that we want to trace, example :
      func (repo *RegisterRepository) getCustomerByEmail(context context.Context, customer *model.Customer, email string) {}
      
      • Use code below for add span
      ctx, span := otel.NewSpan(context, "authregister.RegisterRepository.getCustomerByEmail", "")
      defer span.End()
      
      • Use code below for trace a query
      repo.db.WithContext(ctx).First(customer, "email = ?", strings.ToLower(email))
      
  • Tracing External Service

    • Import package
    otel "github.com/erajayatech/go-opentelemetry"
    
    • Add context argument to function that we want to trace, example :
    func (capillary *Capillary) sendToStagingCustomer(context context.Context, url string, payload interface{}, stagingResponse *StagingCustomerResponse) (*StagingCustomerResponse, error) {}
    
    • Use code below for add span
    httpSpanAttribute := otel.HttpSpanAttribute{}
    httpSpanAttribute.Method = request.Method
    httpSpanAttribute.Url = request.RequestURI
    httpSpanAttribute.IP = request.Host
    
    _, span := otel.NewHttpSpan(context, "capillary.sendToStagingCustomer", url, httpSpanAttribute)
    defer span.End()
    
    • Use code below for add event span
    otel.AddSpanEvents(span, "capillary.sendToStagingCustomer", map[string]string{"traceId": capillary.traceID, "StagCust Endpoint": url, "StagCust Request": string(payloadByte), "StagCustResponse": compactedBuffer.String(), "http.status_code": response.Status})
    

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSpanError

func AddSpanError(span trace.Span, err error)

AddSpanError adds a new event to the span. It will appear under the "Logs" section of the selected span. This is not going to flag the span as "failed". Use this if you think you should log any exceptions such as critical, error, warning, caution etc. Avoid logging sensitive data!

func AddSpanEvents

func AddSpanEvents(span trace.Span, name string, events map[string]string)

AddSpanEvents adds a new events to the span. It will appear under the "Logs" section of the selected span. Use this if the event could mean anything valuable while debugging.

func AddSpanTags

func AddSpanTags(span trace.Span, tags map[string]string)

AddSpanTags adds a new tags to the span. It will appear under "Tags" section of the selected span. Use this if you think the tag and its value could be useful while debugging.

func AnyToBool added in v1.1.0

func AnyToBool(value any) bool

func AppName added in v1.1.0

func AppName() string

func AppVersion added in v1.1.0

func AppVersion() string

func EnvironmentMode added in v1.1.0

func EnvironmentMode() string

func FailSpan

func FailSpan(span trace.Span, msg string)

FailSpan flags the span as "failed" and adds "error" label on listed trace. Use this after calling the `AddSpanError` function so that there is some sort of relevant exception logged against it.

func GenerateMetrics

func GenerateMetrics()

func GetActionName added in v1.1.0

func GetActionName() string

func GetEnv

func GetEnv(key string) string

func GetEnvOrDefault

func GetEnvOrDefault(key string, defaultValue interface{}) interface{}

func GetFunctionName added in v1.1.0

func GetFunctionName(skip int) string

func NewHttpSpan added in v1.0.3

func NewHttpSpan(ctx context.Context, name string, operation string, httpSpanAttribute HttpSpanAttribute) (context.Context, trace.Span)

NewHttpSpan returns a new span from the global tracer. It's can trace an HTTP client request. Each resulting span must be completed with `defer span.End()` right after the call.

func NewRelicTemporalitySelector

func NewRelicTemporalitySelector() aggregation.TemporalitySelector

func NewSpan

func NewSpan(ctx context.Context, name string, operation string) (context.Context, trace.Span)

NewSpan returns a new span from the global tracer. Depending on the `cus` argument, the span is either a plain one or a customised one. Each resulting span must be completed with `defer span.End()` right after the call.

func OtelJaegerURL added in v1.1.0

func OtelJaegerURL() string

func OtelSampled added in v1.1.0

func OtelSampled() bool

func SpanFromContext

func SpanFromContext(ctx context.Context) trace.Span

SpanFromContext returns the current span from a context. If you wish to avoid creating child spans for each operation and just rely on the parent span, use this function throughout the application. With such practise you will get flatter span tree as opposed to deeper version. You can always mix and match both functions.

func Start

func Start(ctx *gin.Context) (context.Context, trace.Span)

func StartWorker added in v1.1.0

func StartWorker(ctx context.Context) (context.Context, trace.Span)

func StringToBool

func StringToBool(value string) bool

func TracerPatch added in v1.2.0

func TracerPatch() (ctx context.Context, reset func())

TracerPatch for unit test monkey patch

func WriteStringTemplate added in v1.1.0

func WriteStringTemplate(stringTemplate string, args ...interface{}) string

Types

type HttpSpanAttribute added in v1.0.3

type HttpSpanAttribute struct {
	Method     string
	Version    string
	Url        string
	IP         string
	StatusCode int
}

type OtelMetricService

type OtelMetricService struct {
	// contains filtered or unexported fields
}

func ConstructMetricOtel

func ConstructMetricOtel() OtelMetricService

func (*OtelMetricService) InitMetricProvider

func (otelMetricService *OtelMetricService) InitMetricProvider(ctx context.Context)

type OtelTracer

type OtelTracer interface {
	SetTraceProviderJaeger() error
	SetTraceProviderNewRelic(ctx context.Context) error
}

func ConstructOtelTracer

func ConstructOtelTracer(options ...OtelTracerOptionFunc) OtelTracer

type OtelTracerOptionFunc added in v1.1.0

type OtelTracerOptionFunc func(*otelTracer)

func IsSampledEnable added in v1.1.0

func IsSampledEnable(isEnabled bool) OtelTracerOptionFunc

func SetApiKey added in v1.2.0

func SetApiKey(key string) OtelTracerOptionFunc

func SetAppName added in v1.1.0

func SetAppName(name string) OtelTracerOptionFunc

func SetEnv added in v1.1.0

func SetEnv(env string) OtelTracerOptionFunc

func SetExporterEndpoint added in v1.2.0

func SetExporterEndpoint(endpoint string) OtelTracerOptionFunc

func SetVersion added in v1.1.0

func SetVersion(version string) OtelTracerOptionFunc

type SpanCustomiser

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

SpanCustomiser is used to enforce custom span options. Any custom concrete span customiser type must implement this interface.

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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