Skip to content

Commit

Permalink
Merge pull request #2569 from sixcolors/2258-logger-latency
Browse files Browse the repository at this point in the history
💄 feat(middleware/logger): latency match gin-gonic/gin formatter
  • Loading branch information
sixcolors authored Aug 11, 2023
2 parents 35a13fb + 35da4c6 commit 2624c5d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
50 changes: 50 additions & 0 deletions middleware/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,56 @@ func Test_Logger_All(t *testing.T) {
utils.AssertEqual(t, expected, buf.String())
}

// go test -run Test_Logger_WithLatency
func Test_Logger_WithLatency(t *testing.T) {
t.Parallel()
buff := bytebufferpool.Get()
defer bytebufferpool.Put(buff)
app := fiber.New()
logger := New(Config{
Output: buff,
Format: "${latency}",
})
app.Use(logger)

// Define a list of time units to test
timeUnits := []struct {
unit string
div time.Duration
}{
// {"ns", time.Nanosecond}, // TODO: Nano seconds are too fast to test
{"µs", time.Microsecond},
{"ms", time.Millisecond},
{"s", time.Second},
}

// Initialize a new time unit
sleepDuration := 1 * time.Nanosecond

// Define a test route that sleeps
app.Get("/test", func(c *fiber.Ctx) error {
time.Sleep(sleepDuration)
return c.SendStatus(fiber.StatusOK)
})

// Loop through each time unit and assert that the log output contains the expected latency value
for _, tu := range timeUnits {
// Update the sleep duration for the next iteration
sleepDuration = 1 * tu.div

// Create a new HTTP request to the test route
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second))
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)

// Assert that the log output contains the expected latency value in the current time unit
utils.AssertEqual(t, bytes.HasSuffix(buff.Bytes(), []byte(tu.unit)), true, "Expected latency to be in %s, got %s", tu.unit, buff.String())

// Reset the buffer
buff.Reset()
}
}

// go test -run Test_Query_Params
func Test_Query_Params(t *testing.T) {
t.Parallel()
Expand Down
2 changes: 1 addition & 1 deletion middleware/logger/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func createTagMap(cfg *Config) map[string]LogFunc {
},
TagLatency: func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (int, error) {
latency := data.Stop.Sub(data.Start)
return output.WriteString(fmt.Sprintf("%7v", latency))
return output.WriteString(fmt.Sprintf("%13v", latency))
},
TagTime: func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (int, error) {
return output.WriteString(data.Timestamp.Load().(string)) //nolint:forcetypeassert // We always store a string in here
Expand Down

0 comments on commit 2624c5d

Please sign in to comment.