Skip to content

Commit

Permalink
🚨 Test: custom-defined Logger and LoggerFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
haochunchang committed Oct 5, 2024
1 parent f293705 commit ea8518b
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions middleware/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"time"

"github.com/gofiber/fiber/v3"
fiberlog "github.com/gofiber/fiber/v3/log"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/stretchr/testify/require"
"github.com/valyala/bytebufferpool"
Expand Down Expand Up @@ -181,6 +182,37 @@ func Test_Logger_ErrorTimeZone(t *testing.T) {
require.Equal(t, fiber.StatusNotFound, resp.StatusCode)
}

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

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

customLoggerFunc := func(c fiber.Ctx, data *Data, cfg Config) error {
cfg.Logger.SetOutput(cfg.Output)
cfg.Logger.SetFlags(0)
cfg.Logger.Error(data.ChainErr.Error())
return nil
}

app.Use(New(Config{
Output: buf,
Logger: fiberlog.DefaultLogger(),
LoggerFunc: customLoggerFunc,
}))

app.Get("/", func(_ fiber.Ctx) error {
return errors.New("some random error")
})

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode)
require.Equal(t, "[Error] some random error\n", buf.String())
}

type fakeErrorOutput int

func (o *fakeErrorOutput) Write([]byte) (int, error) {
Expand Down Expand Up @@ -872,6 +904,31 @@ func Benchmark_Logger_Parallel(b *testing.B) {
benchmarkSetupParallel(bb, app, "/")
})

b.Run("DefaultFormatWithFiberLog", func(bb *testing.B) {
app := fiber.New()
customLoggerFunc := func(c fiber.Ctx, data *Data, cfg Config) error {
cfg.Logger.SetOutput(cfg.Output)
cfg.Logger.SetFlags(0)
cfg.Logger.Infof("%s | %3d | %13v | %15s | %-7s | %-"+data.ErrPaddingStr+"s %s\n",
data.Timestamp.Load().(string),
c.Response().StatusCode(),
data.Stop.Sub(data.Start),
c.IP(), c.Method(), c.Path(),
"",
)
return nil
}
app.Use(New(Config{
Output: io.Discard,
Logger: fiberlog.DefaultLogger(),
LoggerFunc: customLoggerFunc,
}))
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
benchmarkSetupParallel(bb, app, "/")
})

b.Run("DefaultFormatDisableColors", func(bb *testing.B) {
app := fiber.New()
app.Use(New(Config{
Expand Down

0 comments on commit ea8518b

Please sign in to comment.