ft/adds logger to api.server

This commit is contained in:
itsscb 2023-09-22 21:21:45 +02:00
parent 933347095a
commit 83a9648b7a
2 changed files with 48 additions and 1 deletions

36
api/logger.go Normal file
View File

@ -0,0 +1,36 @@
package api
import (
"fmt"
"log/slog"
"time"
"github.com/gin-gonic/gin"
)
func Logger(logger *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
// var buf bytes.Buffer
// tee := io.TeeReader(c.Request.Body, &buf)
// body, _ := io.ReadAll(tee)
// c.Request.Body = io.NopCloser(&buf)
c.Next()
duration := time.Since(t).Milliseconds()
log := []slog.Attr{
slog.String("METHOD", c.Request.Method),
slog.String("PATH", c.Request.RequestURI),
slog.String("DURATION", fmt.Sprintf("%d ms", duration)),
// slog.String("BODY", string(body)),
}
logger.LogAttrs(
c,
slog.LevelDebug,
"http",
log...,
)
}
}

View File

@ -1,6 +1,9 @@
package api
import (
"log/slog"
"os"
"github.com/gin-gonic/gin"
db "github.com/itsscb/df/db/sqlc"
)
@ -17,7 +20,15 @@ func NewServer(store db.Store) *Server {
store: store,
}
router := gin.Default()
opts := slog.HandlerOptions{
Level: slog.LevelDebug,
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts))
router := gin.New()
router.Use(gin.Recovery())
router.Use(Logger(logger))
router.POST("/accounts", server.createAccount)
router.GET("/accounts/:id", server.getAccount)