40 lines
851 B
Go
40 lines
851 B
Go
package server
|
|
|
|
import (
|
|
"git.sr.ht/~cco/go-scopes/lib"
|
|
"git.sr.ht/~cco/go-scopes/logging"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/rs/zerolog"
|
|
)
|
|
|
|
func Logger(ctx lib.Context) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// before request
|
|
// t := time.Now()
|
|
path := c.Request.URL.Path
|
|
raw := c.Request.URL.RawQuery
|
|
if raw != "" {
|
|
path = path + "?" + raw
|
|
}
|
|
c.Next()
|
|
// after request
|
|
msg := c.Errors.String()
|
|
if msg == "" {
|
|
msg = "request"
|
|
}
|
|
status := c.Writer.Status()
|
|
var evt *zerolog.Event
|
|
switch {
|
|
case status >= 500:
|
|
evt = logging.Error(ctx)
|
|
case status >= 400:
|
|
evt = logging.Warn(ctx)
|
|
default:
|
|
evt = logging.Info(ctx)
|
|
}
|
|
evt.Str("method", c.Request.Method).Str("path", path).
|
|
// Dur("resp_time", time.Since(t)).
|
|
Int("status", status).
|
|
Str("client_ip", c.ClientIP()).Msg(msg)
|
|
}
|
|
}
|