2fas-server/internal/common/http/log.go

64 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-12-31 10:22:38 +01:00
package http
import (
"bytes"
2023-05-22 19:31:54 +02:00
"io"
2022-12-31 10:22:38 +01:00
"github.com/gin-gonic/gin"
2024-03-16 19:05:21 +01:00
"github.com/google/uuid"
2023-01-30 19:59:42 +01:00
"github.com/twofas/2fas-server/internal/common/logging"
2022-12-31 10:22:38 +01:00
)
2024-03-16 19:05:21 +01:00
const (
CorrelationIdHeader = "X-Correlation-ID"
)
var (
RequestId string
CorrelationId string
)
func LoggingMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
requestId := uuid.New().String()
correlationId := c.Request.Header.Get(CorrelationIdHeader)
if correlationId == "" {
correlationId = uuid.New().String()
}
ctxWithLog := logging.AddToContext(c.Request.Context(), logging.WithFields(map[string]any{
"correlation_id": correlationId,
"request_id": requestId,
}))
c.Request = c.Request.WithContext(ctxWithLog)
}
}
2022-12-31 10:22:38 +01:00
func RequestJsonLogger() gin.HandlerFunc {
return func(c *gin.Context) {
var buf bytes.Buffer
tee := io.TeeReader(c.Request.Body, &buf)
body, _ := io.ReadAll(tee)
c.Request.Body = io.NopCloser(&buf)
2024-03-16 19:05:21 +01:00
log := logging.FromContext(c.Request.Context())
log.WithFields(logging.Fields{
"method": c.Request.Method,
"path": c.Request.URL.Path,
"body": string(body),
}).Info("Request")
2022-12-31 10:22:38 +01:00
c.Next()
2024-03-16 19:05:21 +01:00
log.WithFields(logging.Fields{
"method": c.Request.Method,
"path": c.Request.URL.Path,
}).Info("Response")
2022-12-31 10:22:38 +01:00
}
}