pkg/tracing/tracing.go

63 lines
1.5 KiB
Go
Raw Normal View History

2023-04-09 06:54:54 +00:00
package tracing
2023-04-09 06:30:15 +00:00
import (
2023-04-09 15:04:57 +00:00
"context"
"fmt"
2023-04-09 06:30:15 +00:00
"net/http"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
2023-04-09 15:04:57 +00:00
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"git.ifooth.com/common/pkg/config"
"git.ifooth.com/common/pkg/version"
2023-04-09 06:30:15 +00:00
)
// TracingHandler
func TracingHandler(operation string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
}
return otelhttp.NewHandler(http.HandlerFunc(fn), operation)
}
}
2023-04-09 15:04:57 +00:00
// newResource
func NewResource(serviceName, runEnv string) (*resource.Resource, error) {
r, err := resource.Merge(
resource.Default(),
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceName(serviceName),
semconv.ServiceVersion(version.Version),
attribute.String("run_env", runEnv),
),
)
if err != nil {
return nil, fmt.Errorf("creating trace resource: %w", err)
}
return r, nil
}
// newExporter
func NewExporter(ctx context.Context, conf *config.Tracing) (trace.SpanExporter, error) {
client := otlptracegrpc.NewClient(
otlptracegrpc.WithEndpoint(conf.Endpoint),
otlptracegrpc.WithInsecure(),
)
exporter, err := otlptrace.New(ctx, client)
if err != nil {
return nil, fmt.Errorf("creating OTLP trace exporter: %w", err)
}
return exporter, nil
}