🤗 Strange behaviour of the logger when adding tag "method" TagMethod into formatting string
v 2.21.0
Adding tag "method" TagMethod in custom format, force using of the default formatting and completely ignoring custom one
Magic is in a function https://github.com/gofiber/fiber/blob/85591e8b45fb406fb79104402cb6b7f72ec284c0/middleware/logger/config.go#L61 checking for 2 keywords one of them is "method", used in configDefault https://github.com/gofiber/fiber/blob/85591e8b45fb406fb79104402cb6b7f72ec284c0/middleware/logger/config.go#L85 A decision is made to enable colors in configuration.
cfg.enableColors = true
Which is the root of the problem because same flag is used in decision, default formatting to be used. :flushed: https://github.com/gofiber/fiber/blob/85591e8b45fb406fb79104402cb6b7f72ec284c0/middleware/logger/logger.go#L177 Code snippet
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
func main() {
app := fiber.New()
// Steps to reproduce
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
log.Fatal(app.Listen(":3000"))
}
Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord
Related to https://github.com/gofiber/fiber/pull/1513/files
@amalshaji
interesting. I will look into it.
Previous solution to fixing the custom color issue was okay, but did not take into account how the coloring was done in the background. Here, if colors are enabled, it colors the default format. Because the previous fix did not account for the custom template.
Solution is to make changes to this switch tag
if validCustomFormat(cfg.Format) && cfg.Output == nil {
cfg.enableColors = 0
}
if cfg.Format == "" && cfg.Output == nil {
cfg.enableColors = 1
}
Line 177 becomes,
if cfg.enableColors == 1 {
....
}
Line 240 becomes,
case TagStatus:
if cfg.enableColors == 0 {
resp := fmt.Sprintf("%s %3d %s", statusColor(c.Response().StatusCode()), c.Response().StatusCode(), cReset)
return appendInt(buf, resp)
}
return appendInt(buf, c.Response().StatusCode())
Similar change to Line 246
A lot of changes here. There's also a case of tests. What do you think?
Probably question is not for me, but I think that flag cfg.enableColors has no place in configuration and the way it is tested (cfg.Format == "" && cfg.Output == nil) does not correspond to it's name. Maybe there is a need for deeper refactoring.