fix(output.datadog): log response in case of non 2XX response from API (#12201)

This commit is contained in:
Neelay Upadhyaya 2022-11-22 02:24:24 +05:30 committed by GitHub
parent 960a1f7b14
commit 6f407c5949
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 8 deletions

View File

@ -6,6 +6,7 @@ import (
_ "embed"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
@ -168,7 +169,9 @@ func (d *Datadog) Write(metrics []telegraf.Metric) error {
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 209 {
return fmt.Errorf("received bad status code, %d", resp.StatusCode)
// err can be ignored
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("received bad status code, %d: %s", resp.StatusCode, string(body))
}
return nil

View File

@ -24,6 +24,7 @@ var (
func NewDatadog(url string) *Datadog {
return &Datadog{
URL: url,
Log: testutil.Logger{},
}
}
@ -67,14 +68,10 @@ func TestCompressionOverride(t *testing.T) {
}
func TestBadStatusCode(t *testing.T) {
errorString := `{"errors": ["Something bad happened to the server.", "Your query made the server very sad."]}`
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
//nolint:errcheck,revive // Ignore the returned error as the test will fail anyway
json.NewEncoder(w).Encode(`{ 'errors': [
'Something bad happened to the server.',
'Your query made the server very sad.'
]
}`)
fmt.Fprint(w, errorString)
}))
defer ts.Close()
@ -86,7 +83,7 @@ func TestBadStatusCode(t *testing.T) {
if err == nil {
t.Errorf("error expected but none returned")
} else {
require.EqualError(t, fmt.Errorf("received bad status code, 500"), err.Error())
require.EqualError(t, err, fmt.Sprintf("received bad status code, %v: %s", http.StatusInternalServerError, errorString))
}
}