Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

otelfiber: Add custom attributes support #700

Merged
merged 3 commits into from
Aug 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions otelfiber/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ otelfiber.Middleware(opts ...otelfiber.Option) fiber.Handler
| Propagators | `propagation.TextMapPropagator` | Specifies propagators to use for extracting information from the HTTP requests | If none are specified, global ones will be used |
| ServerName | `*string` | specifies the value to use when setting the `http.server_name` attribute on metrics/spans | - |
| SpanNameFormatter | `func(*fiber.Ctx) string` | Takes a function that will be called on every request and the returned string will become the Span Name | default formatter returns the route pathRaw |
| CustomAttributes | `func(*fiber.Ctx) []attribute.KeyValue` | Define a function to add custom attributes to the span | nil |

## Usage

Expand Down
9 changes: 9 additions & 0 deletions otelfiber/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package otelfiber

import (
"github.com/gofiber/fiber/v2"
"go.opentelemetry.io/otel/attribute"
otelmetric "go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
oteltrace "go.opentelemetry.io/otel/trace"
Expand All @@ -16,6 +17,7 @@ type config struct {
Propagators propagation.TextMapPropagator
ServerName *string
SpanNameFormatter func(*fiber.Ctx) string
CustomAttributes func(*fiber.Ctx) []attribute.KeyValue
}

// Option specifies instrumentation configuration options.
Expand Down Expand Up @@ -87,3 +89,10 @@ func WithPort(port int) Option {
})
}

// WithCustomAttributes specifies a function that will be called on every
// request and the returned attributes will be added to the span.
func WithCustomAttributes(f func(ctx *fiber.Ctx) []attribute.KeyValue) Option {
return optionFunc(func(cfg *config) {
cfg.CustomAttributes = f
})
}
46 changes: 46 additions & 0 deletions otelfiber/fiber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,3 +401,49 @@ func getHistogram(value float64, attrs []attribute.KeyValue) metricdata.Histogra
Temporality: metricdata.CumulativeTemporality,
}
}

func TestCustomAttributes(t *testing.T) {
sr := new(oteltest.SpanRecorder)
provider := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr))

var gotSpan oteltrace.Span

app := fiber.New()
app.Use(
Middleware(
WithTracerProvider(provider),
WithCustomAttributes(func(ctx *fiber.Ctx) []attribute.KeyValue {
return []attribute.KeyValue{
attribute.Key("http.query_params").String(ctx.Request().URI().QueryArgs().String()),
}
}),
),
)

app.Get("/user/:id", func(ctx *fiber.Ctx) error {
gotSpan = oteltrace.SpanFromContext(ctx.UserContext())
id := ctx.Params("id")
return ctx.SendString(id)
})

resp, _ := app.Test(httptest.NewRequest("GET", "/user/123?foo=bar", nil), 3000)

// do and verify the request
require.Equal(t, http.StatusOK, resp.StatusCode)

mspan, ok := gotSpan.(*oteltest.Span)
require.True(t, ok)
assert.Equal(t, attribute.StringValue("foo=bar"), mspan.Attributes()["http.query_params"])

// verify traces look good
spans := sr.Completed()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "/user/:id", span.Name())
assert.Equal(t, oteltrace.SpanKindServer, span.SpanKind())
assert.Equal(t, attribute.IntValue(http.StatusOK), span.Attributes()["http.status_code"])
assert.Equal(t, attribute.StringValue("GET"), span.Attributes()["http.method"])
assert.Equal(t, attribute.StringValue("/user/123?foo=bar"), span.Attributes()["http.target"])
assert.Equal(t, attribute.StringValue("/user/:id"), span.Attributes()["http.route"])
assert.Equal(t, attribute.StringValue("foo=bar"), span.Attributes()["http.query_params"])
}
4 changes: 4 additions & 0 deletions otelfiber/semconv.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ func httpServerTraceAttributesFromRequest(c *fiber.Ctx, cfg config) []attribute.
attrs = append(attrs, semconv.HTTPClientIPKey.String(utils.CopyString(clientIP)))
}

if cfg.CustomAttributes != nil {
attrs = append(attrs, cfg.CustomAttributes(c)...)
}

return attrs
}

Expand Down
Loading