-
Notifications
You must be signed in to change notification settings - Fork 4
/
fiberlog.go
83 lines (70 loc) · 1.72 KB
/
fiberlog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package fiberlog
import (
"net/http"
"os"
"time"
"github.com/gofiber/fiber"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Config defines the config for logger middleware.
type Config struct {
// Next defines a function to skip this middleware.
Next func(ctx *fiber.Ctx) bool
// Logger is a *zerolog.Logger that writes the logs.
//
// Default: log.Logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
Logger *zerolog.Logger
}
// New is a zerolog middleware that allows you to pass a Config.
//
// app := fiber.New()
//
// // Without config
// app.Use(New())
//
// // With config
// app.Use(New(Config{Logger: &zerolog.New(os.Stdout)}))
func New(config ...Config) fiber.Handler {
var conf Config
if len(config) > 0 {
conf = config[0]
}
var sublog zerolog.Logger
if conf.Logger == nil {
sublog = log.Logger.Output(zerolog.ConsoleWriter{Out: os.Stderr})
} else {
sublog = *conf.Logger
}
return func(c *fiber.Ctx) {
// Don't execute the middleware if Next returns true
if conf.Next != nil && conf.Next(c) {
c.Next()
return
}
start := time.Now()
// handle request
c.Next()
msg := "Request"
if err := c.Error(); err != nil {
msg = err.Error()
}
code := c.Fasthttp.Response.StatusCode()
dumplogger := sublog.With().
Int("status", code).
Str("method", c.Method()).
Str("path", c.Path()).
Str("ip", c.IP()).
Str("latency", time.Since(start).String()).
Str("user-agent", c.Get(fiber.HeaderUserAgent)).
Logger()
switch {
case code >= fiber.StatusBadRequest && code < fiber.StatusInternalServerError:
dumplogger.Warn().Msg(msg)
case code >= http.StatusInternalServerError:
dumplogger.Error().Msg(msg)
default:
dumplogger.Info().Msg(msg)
}
}
}