use zerolog logger for gin server

This commit is contained in:
Helmut Merz 2023-07-01 14:18:11 +02:00
parent c6ac480ad7
commit 4e06072d96
3 changed files with 45 additions and 2 deletions

40
server/logger.go Normal file
View file

@ -0,0 +1,40 @@
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)
}
}

View file

@ -19,6 +19,7 @@ type ServerState struct {
}
func Start(ctx lib.Context) {
gin.SetMode(gin.ReleaseMode)
lib.GetCfg[*Cfg](ctx).BaseCfg.WithDoneHandler(HandleDone)
Serve(ctx)
lib.RunCtx(ctx, core.Listen)
@ -30,7 +31,9 @@ func HandleDone(ctx lib.Context) bool {
}
func Serve(ctx lib.Context) {
r := gin.Default()
//r := gin.Default()
r := gin.New()
r.Use(Logger(ctx))
r.GET("/*action", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})

View file

@ -19,7 +19,7 @@ func TestConfig(tb *tbase.T) {
t.Run("send", SendTest)
t.Run("client", ClientTest)
t.TearDownApp()
t.AssertEqual(t.LogCount(true), 11)
t.AssertEqual(t.LogCount(true), 12)
}
func AppTest(t *testing.T) {