Skip to content

Commit

Permalink
fix: log as array of attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
MegaportPhilipBrowne committed Oct 2, 2024
1 parent 2378bfc commit 619b979
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 21 deletions.
29 changes: 11 additions & 18 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,14 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*htt
reqTime := time.Since(reqStart)

respBody := resp.Body

attrs := []slog.Attr{slog.Duration("duration", reqTime),
slog.Int("status_code", resp.StatusCode),
slog.String("path", req.URL.EscapedPath()),
slog.String("api_host", c.BaseURL.Host),
slog.String("method", req.Method),
slog.String("trace_id", resp.Header.Get(headerTraceId))}

if c.LogResponseBody {
b, err := io.ReadAll(resp.Body)
if err != nil {
Expand All @@ -302,26 +310,11 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*htt
// Create new reader for the later code
respBody = io.NopCloser(bytes.NewReader(b))

// Log With Response Body
c.Logger.DebugContext(ctx, "completed API request", //nolint:sloglint
slog.Duration("duration", reqTime),
slog.Int("status_code", resp.StatusCode),
slog.String("path", req.URL.EscapedPath()),
slog.String("api_host", c.BaseURL.Host),
slog.String("method", req.Method),
slog.String("trace_id", resp.Header.Get(headerTraceId)),
slog.String("response_body_base64", encodedBody)) // Response Body is Base64 Encoded
} else { // Log Without Response Body
c.Logger.DebugContext(ctx, "completed API request", //nolint:sloglint
slog.Duration("duration", reqTime),
slog.Int("status_code", resp.StatusCode),
slog.String("path", req.URL.EscapedPath()),
slog.String("api_host", c.BaseURL.Host),
slog.String("method", req.Method),
slog.String("trace_id", resp.Header.Get(headerTraceId)),
)
attrs = append(attrs, slog.String("response_body_base_64", encodedBody))
}

c.Logger.DebugContext(ctx, "completed api request", slog.Any("api_request", attrs))

err = CheckResponse(resp)
if err != nil {
return nil, err
Expand Down
13 changes: 10 additions & 3 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,10 @@ func (suite *ClientTestSuite) TestNewRequest_withResponseLogging() {
mockResponse := `{"message": "success"}`
mockServer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(mockResponse))
_, err := w.Write([]byte(mockResponse))
if err != nil {
suite.FailNowf("Write() unexpected error: %v", err.Error())
}
})
server := httptest.NewServer(mockServer)
defer server.Close()
Expand Down Expand Up @@ -179,7 +182,7 @@ func (suite *ClientTestSuite) TestNewRequest_withResponseLogging() {

// Log the response body
encodedBody := base64.StdEncoding.EncodeToString(body)
c.Logger.DebugContext(ctx, "response body", slog.String("response_body_base64", encodedBody))
c.Logger.DebugContext(ctx, "response body", slog.String("response_body_base_64", encodedBody))

Check failure on line 185 in client_test.go

View workflow job for this annotation

GitHub Actions / lint

keys should be written in snake_case (sloglint)

// Check the response
var result map[string]interface{}
Expand All @@ -188,7 +191,11 @@ func (suite *ClientTestSuite) TestNewRequest_withResponseLogging() {
}

expectedMessage := "success"
resultMsg := result["message"].(string)
resultMsg, ok := result["message"].(string)
if !ok {
suite.FailNow("Response message is not a string")
}

if result["message"] != expectedMessage {
suite.FailNowf("Response message = %s; expected %s", resultMsg, expectedMessage)
}
Expand Down

0 comments on commit 619b979

Please sign in to comment.