74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
|
package fiber_tracing
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"log"
|
||
|
|
||
|
"github.com/gofiber/fiber/v2"
|
||
|
fiberOpentelemetry "github.com/psmarcin/fiber-opentelemetry/pkg/fiber-otel"
|
||
|
"go.opentelemetry.io/otel"
|
||
|
"go.opentelemetry.io/otel/attribute"
|
||
|
"go.opentelemetry.io/otel/sdk/resource"
|
||
|
trc "go.opentelemetry.io/otel/sdk/trace"
|
||
|
semconv "go.opentelemetry.io/otel/semconv/v1.25.0"
|
||
|
trace "go.opentelemetry.io/otel/trace"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
TracingError error = nil
|
||
|
TP trc.TracerProvider
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
AppName string
|
||
|
Version string
|
||
|
ServiceProvider string
|
||
|
Exporter trc.SpanExporter
|
||
|
}
|
||
|
|
||
|
func newResource(config Config) *resource.Resource {
|
||
|
r := resource.NewWithAttributes(
|
||
|
semconv.SchemaURL,
|
||
|
semconv.ServiceNameKey.String(config.AppName),
|
||
|
semconv.ServiceVersionKey.String(config.Version),
|
||
|
attribute.String("service.provider", config.ServiceProvider),
|
||
|
)
|
||
|
return r
|
||
|
}
|
||
|
|
||
|
func NewMiddleware(config Config) func(*fiber.Ctx) error {
|
||
|
var tracerProviders []trc.TracerProviderOption
|
||
|
|
||
|
tracerProviders = append(tracerProviders, trc.WithBatcher(config.Exporter))
|
||
|
tracerProviders = append(tracerProviders, trc.WithResource(newResource(config)))
|
||
|
|
||
|
TP = *trc.NewTracerProvider(tracerProviders...)
|
||
|
|
||
|
otel.SetTracerProvider(&TP)
|
||
|
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {
|
||
|
if err != TracingError {
|
||
|
TracingError = err
|
||
|
log.Println(err)
|
||
|
}
|
||
|
}))
|
||
|
|
||
|
tracer := TP.Tracer("_maal-fiber-otel_")
|
||
|
|
||
|
return fiberOpentelemetry.New(
|
||
|
fiberOpentelemetry.Config{
|
||
|
Tracer: tracer,
|
||
|
SpanName: "{{ .Method }} {{ .Path }}",
|
||
|
TracerStartAttributes: []trace.SpanStartOption{
|
||
|
trace.WithSpanKind(trace.SpanKindServer),
|
||
|
trace.WithNewRoot(),
|
||
|
},
|
||
|
},
|
||
|
)
|
||
|
}
|
||
|
|
||
|
func ShutdownTracer() {
|
||
|
if err := TP.Shutdown(context.Background()); err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
}
|