Skip to content

Commit

Permalink
optimize: set byteSent log to 0 when use SetBodyStreamWriter (#2239)
Browse files Browse the repository at this point in the history
  • Loading branch information
li-jin-gou committed Dec 1, 2022
1 parent f367916 commit 075dfc5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
41 changes: 41 additions & 0 deletions middleware/logger/logger_test.go
@@ -1,6 +1,7 @@
package logger

import (
"bufio"
"bytes"
"errors"
"fmt"
Expand All @@ -10,6 +11,7 @@ import (
"os"
"sync"
"testing"
"time"

"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
Expand Down Expand Up @@ -441,3 +443,42 @@ func Test_CustomTags(t *testing.T) {
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)
utils.AssertEqual(t, customTag, buf.String())
}

// go test -run Test_Logger_ByteSent_Streaming
func Test_Logger_ByteSent_Streaming(t *testing.T) {
app := fiber.New()

buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

app.Use(New(Config{
Format: "${bytesReceived} ${bytesSent} ${status}",
Output: buf,
}))

app.Get("/", func(c *fiber.Ctx) error {
c.Set("Connection", "keep-alive")
c.Set("Transfer-Encoding", "chunked")
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
var i int
for {
i++
msg := fmt.Sprintf("%d - the time is %v", i, time.Now())
fmt.Fprintf(w, "data: Message: %s\n\n", msg)
err := w.Flush()
if err != nil {
break
}
if i == 10 {
break
}
}
})
return nil
})

resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode)
utils.AssertEqual(t, "0 0 200", buf.String())
}
3 changes: 3 additions & 0 deletions middleware/logger/tags.go
Expand Up @@ -89,6 +89,9 @@ func createTagMap(cfg *Config) map[string]LogFunc {
return appendInt(output, len(c.Request().Body()))
},
TagBytesSent: func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (int, error) {
if c.Response().Header.ContentLength() < 0 {
return appendInt(output, 0)
}
return appendInt(output, len(c.Response().Body()))
},
TagRoute: func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (int, error) {
Expand Down

1 comment on commit 075dfc5

@ReneWerner87
Copy link
Member

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 2.

Benchmark suite Current: 075dfc5 Previous: f367916 Ratio
Benchmark_App_ETag 6886 ns/op 1044 B/op 3 allocs/op 3250 ns/op 1044 B/op 3 allocs/op 2.12

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.