Skip to content

Commit 10b26af

Browse files
Swopxvzf
authored andcommitted
fix: fiber log middleware log fields + lint
1 parent 580ccde commit 10b26af

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

pkg/util/logger/fiber.go

+13-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package logger
22

33
import (
4+
"fmt"
45
"time"
56

67
"github.com/gofiber/fiber/v2"
@@ -12,42 +13,42 @@ const (
1213
)
1314

1415
func FiberMiddleware(logger zerolog.Logger) fiber.Handler {
15-
1616
return func(c *fiber.Ctx) error {
17-
1817
log := logger.With().Logger()
1918

2019
// if traceparent is present, add it to the log
2120
if traceparent := c.Get(TraceparentHeaderName, ""); traceparent != "" {
2221
log = logger.With().Str("req_trace_parent", traceparent).Logger()
2322
}
24-
2523
ctx := log.WithContext(c.UserContext())
2624
c.SetUserContext(ctx)
2725

2826
start := time.Now()
2927

30-
msg := ""
28+
msg := "Request"
3129
err := c.Next()
3230
if err != nil {
3331
msg = err.Error()
3432
_ = c.SendStatus(fiber.StatusInternalServerError)
3533
}
3634

3735
log = log.With().
38-
Int("status", c.Response().StatusCode()).
39-
Str("latency", time.Since(start).String()).
40-
Str("method", c.Method()).
41-
Str("path", c.Path()).
42-
Str("protocol", c.Protocol()).
36+
Int("req_status", c.Response().StatusCode()).
37+
Str("req_latency", fmt.Sprintf("%.3f", float64(time.Since(start).Microseconds())/1000)).
38+
Str("req_method", c.Method()).
39+
Str("req_ip", c.IP()).
40+
Str("req_path", c.Path()).
41+
Str("req_proto", c.Protocol()).
42+
Str("req_user_agent", c.Get(fiber.HeaderUserAgent)).
4343
Logger()
4444

4545
// Set loglevel based on status code
46-
if c.Response().StatusCode() >= fiber.StatusInternalServerError {
46+
switch {
47+
case c.Response().StatusCode() >= fiber.StatusInternalServerError:
4748
log.Error().Msg(msg)
48-
} else if c.Response().StatusCode() >= fiber.StatusBadRequest {
49+
case c.Response().StatusCode() >= fiber.StatusBadRequest:
4950
log.Warn().Msg(msg)
50-
} else {
51+
default:
5152
log.Info().Msg(msg)
5253
}
5354

0 commit comments

Comments
 (0)