feat: complete SOP version management
This commit is contained in:
@@ -24,9 +24,10 @@ func RequestLogger(log *zap.Logger) gin.HandlerFunc {
|
||||
c.Header("X-Request-ID", requestID)
|
||||
c.Next()
|
||||
|
||||
duration := time.Since(started)
|
||||
fields := []zap.Field{
|
||||
zap.String("request_id", requestID), zap.String("method", c.Request.Method), zap.String("path", c.Request.URL.Path),
|
||||
zap.Int("status", c.Writer.Status()), zap.Int("response_bytes", c.Writer.Size()), zap.Duration("duration", time.Since(started)), zap.String("client_ip", c.ClientIP()),
|
||||
zap.Int("status", c.Writer.Status()), zap.Int("response_bytes", c.Writer.Size()), zap.Int64("duration_ms", duration.Milliseconds()), zap.String("client_ip", c.ClientIP()),
|
||||
}
|
||||
if principal, ok := auth.PrincipalFromContext(c); ok {
|
||||
fields = append(fields, zap.Uint64("tenant_id", principal.TenantID), zap.Uint64("user_id", principal.UserID))
|
||||
@@ -34,7 +35,14 @@ func RequestLogger(log *zap.Logger) gin.HandlerFunc {
|
||||
if len(c.Errors) > 0 {
|
||||
fields = append(fields, zap.String("errors", c.Errors.String()))
|
||||
}
|
||||
log.Info("http request", fields...)
|
||||
switch status := c.Writer.Status(); {
|
||||
case status >= http.StatusInternalServerError:
|
||||
log.Error("http request", fields...)
|
||||
case status >= http.StatusBadRequest:
|
||||
log.Warn("http request", fields...)
|
||||
default:
|
||||
log.Info("http request", fields...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
32
internal/middleware/http_test.go
Normal file
32
internal/middleware/http_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
func TestRequestLoggerUsesStatusLevelAndDurationMilliseconds(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
core, logs := observer.New(zapcore.DebugLevel)
|
||||
router := gin.New()
|
||||
router.Use(RequestLogger(zap.New(core)))
|
||||
router.GET("/bad", func(c *gin.Context) { c.Status(http.StatusBadRequest) })
|
||||
|
||||
request := httptest.NewRequest(http.MethodGet, "/bad", nil)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
|
||||
entries := logs.All()
|
||||
if len(entries) != 1 || entries[0].Level != zapcore.WarnLevel {
|
||||
t.Fatalf("log entries = %+v, want one warning", entries)
|
||||
}
|
||||
if _, exists := entries[0].ContextMap()["duration_ms"]; !exists {
|
||||
t.Fatalf("duration_ms is missing from request log")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user