add logs using log/slog (#23)

This commit is contained in:
itsscb 2023-09-23 20:29:14 +02:00 committed by GitHub
parent 3d4b84fbe2
commit 411d3ff6a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 66 additions and 17 deletions

View File

@ -1,34 +1,74 @@
package api package api
import ( import (
"bytes"
"fmt" "fmt"
"io"
"log/slog" "log/slog"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func Logger(logger *slog.Logger) gin.HandlerFunc { type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (r responseBodyWriter) Write(b []byte) (int, error) {
r.body.Write(b)
return r.ResponseWriter.Write(b)
}
func Logger() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
t := time.Now() t := time.Now()
var log []slog.Attr
var body []byte
var w *responseBodyWriter
if c.Request.Method != "GET" {
body, _ = io.ReadAll(c.Request.Body)
w = &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
c.Writer = w
c.Request.Body = io.NopCloser(bytes.NewReader(body))
}
c.Next() c.Next()
duration := time.Since(t).Milliseconds() duration := time.Since(t).Milliseconds()
log = append(log, if c.Request.Method != "GET" {
slog.Int("STATUS", c.Writer.Status()), slog.LogAttrs(
slog.String("METHOD", c.Request.Method), c,
slog.String("PATH", c.Request.RequestURI), slog.LevelDebug,
slog.String("DURATION", fmt.Sprintf("%d ms", duration)), "http",
) slog.Group(
"request",
slog.Int("STATUS", c.Writer.Status()),
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)),
),
slog.Group(
"response",
slog.String("BODY", w.body.String()),
),
)
} else {
slog.LogAttrs(
c,
slog.LevelDebug,
"http",
slog.Group(
"request",
slog.Int("STATUS", c.Writer.Status()),
slog.String("METHOD", c.Request.Method),
slog.String("PATH", c.Request.RequestURI),
slog.String("DURATION", fmt.Sprintf("%d ms", duration)),
),
)
logger.LogAttrs( }
c,
slog.LevelDebug,
"http",
log...,
)
} }
} }

View File

@ -31,12 +31,19 @@ func NewServer(config util.Config, store db.Store) *Server {
opts := slog.HandlerOptions{ opts := slog.HandlerOptions{
Level: logLevel, Level: logLevel,
} }
logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts)) logger := slog.New(slog.NewTextHandler(os.Stdout, &opts))
if config.LogOutput == "json" {
logger = slog.New(slog.NewJSONHandler(os.Stdout, &opts))
}
slog.SetDefault(logger)
router := gin.New() router := gin.New()
router.Use(gin.Recovery()) router.Use(gin.Recovery())
router.Use(Logger(logger)) router.Use(Logger())
router.POST("/accounts", server.createAccount) router.POST("/accounts", server.createAccount)
router.GET("/accounts/:id", server.getAccount) router.GET("/accounts/:id", server.getAccount)

View File

@ -1,4 +1,5 @@
DB_SOURCE=postgresql://root:secret@localhost:5432/df?sslmode=disable DB_SOURCE=postgresql://root:secret@localhost:5432/df?sslmode=disable
DB_DRIVER=postgres DB_DRIVER=postgres
SERVER_ADDRESS=0.0.0.0:8080 SERVER_ADDRESS=0.0.0.0:8080
ENVIRONMENT=development ENVIRONMENT=development
LOG_OUTPUT=text

View File

@ -7,6 +7,7 @@ type Config struct {
DBDriver string `mapstructure:"DB_DRIVER"` DBDriver string `mapstructure:"DB_DRIVER"`
ServerAddress string `mapstructure:"SERVER_ADDRESS"` ServerAddress string `mapstructure:"SERVER_ADDRESS"`
Environment string `mapstructure:"ENVIRONMENT"` Environment string `mapstructure:"ENVIRONMENT"`
LogOutput string `mapstructure:"LOG_OUTPUT"`
} }
func LoadConfig(path string) (config Config, err error) { func LoadConfig(path string) (config Config, err error) {