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

contrib/go-chi/chi: Added option to set custom error status check #773

Merged
merged 8 commits into from
Dec 11, 2020
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
2 changes: 1 addition & 1 deletion contrib/go-chi/chi/chi.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func Middleware(opts ...Option) func(next http.Handler) http.Handler {
}
span.SetTag(ext.HTTPCode, strconv.Itoa(status))

if status >= 500 && status < 600 {
if cfg.isError(status) {
// mark 5xx server error
span.SetTag(ext.Error, fmt.Errorf("%d: %s", status, http.StatusText(status)))
}
Expand Down
96 changes: 69 additions & 27 deletions contrib/go-chi/chi/chi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"

"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
Expand Down Expand Up @@ -99,37 +100,78 @@ func TestTrace200(t *testing.T) {
}

func TestError(t *testing.T) {
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()
assertSpan := func(assert *assert.Assertions, spans []mocktracer.Span, code int) {
assert.Len(spans, 1)
if len(spans) < 1 {
t.Fatalf("no spans")
}
span := spans[0]
assert.Equal("http.request", span.OperationName())
assert.Equal("foobar", span.Tag(ext.ServiceName))

// setup
router := chi.NewRouter()
router.Use(Middleware(WithServiceName("foobar")))
code := 500
wantErr := fmt.Sprintf("%d: %s", code, http.StatusText(code))
assert.Equal(strconv.Itoa(code), span.Tag(ext.HTTPCode))

wantErr := fmt.Sprintf("%d: %s", code, http.StatusText(code))
assert.Equal(wantErr, span.Tag(ext.Error).(error).Error())
}
knusbaum marked this conversation as resolved.
Show resolved Hide resolved
t.Run("with default isError function", func(t *testing.T) {
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()

// setup
router := chi.NewRouter()
router.Use(Middleware(WithServiceName("foobar")))
code := 500

// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, code)

// verify the errors and status are correct
spans := mt.FinishedSpans()
assertSpan(assert, spans, code)

// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, 500)

// verify the errors and status are correct
spans := mt.FinishedSpans()
assert.Len(spans, 1)
if len(spans) < 1 {
t.Fatalf("no spans")
}
span := spans[0]
assert.Equal("http.request", span.OperationName())
assert.Equal("foobar", span.Tag(ext.ServiceName))
assert.Equal("500", span.Tag(ext.HTTPCode))
assert.Equal(wantErr, span.Tag(ext.Error).(error).Error())
t.Run("with custome isError function", func(t *testing.T) {
Hunrik marked this conversation as resolved.
Show resolved Hide resolved
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()

// setup
router := chi.NewRouter()

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's eliminate this whitespace as it doesn't make the test easier to read.

router.Use(Middleware(
WithServiceName("foobar"),
WithIsErrorCheck(func(statusCode int) bool {
return statusCode >= 400
}),
))

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here with whitespace. I think we can remove it.

code := 404

// a handler with an error and make the requests
router.Get("/err", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("%d!", code), code)
})
r := httptest.NewRequest("GET", "/err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result()
assert.Equal(response.StatusCode, code)

// verify the errors and status are correct
spans := mt.FinishedSpans()
assertSpan(assert, spans, code)
})

}

func TestGetSpanNotInstrumented(t *testing.T) {
Expand Down
15 changes: 15 additions & 0 deletions contrib/go-chi/chi/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type config struct {
serviceName string
spanOpts []ddtrace.StartSpanOption // additional span options to be applied
analyticsRate float64
isError func(statusCode int) bool
}

// Option represents an option that can be passed to NewRouter.
Expand All @@ -32,6 +33,8 @@ func defaults(cfg *config) {
} else {
cfg.analyticsRate = globalconfig.AnalyticsRate()
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for the empty line here.

cfg.isError = defaultIsError
}

// WithServiceName sets the given service name for the router.
Expand Down Expand Up @@ -71,3 +74,15 @@ func WithAnalyticsRate(rate float64) Option {
}
}
}

// WithIsErrorCheck sets the function which is used to decide whther the
// status should be marked as an error
func WithIsErrorCheck(isError func(statusCode int) bool) Option {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm more inclined towards something like WithStatusCheck or WithErrorCheck. WithIsErrorCheck is a little cumbersome.

What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WithStatusCheck Sounds better to me too.

return func(cfg *config) {
cfg.isError = isError
}
}

func defaultIsError(statusCode int) bool {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would probably be clearer to call this isServerError to indicate it checks for 5xx error codes.

return statusCode >= 500 && statusCode < 600
}