75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type RequestLogger struct {
|
|
RequestID string `json:"request_id"`
|
|
Method string `json:"method"`
|
|
Path string `json:"path"`
|
|
Status int `json:"status"`
|
|
Duration time.Duration `json:"duration_ms"`
|
|
UserID string `json:"user_id,omitempty"`
|
|
ClientIP string `json:"client_ip"`
|
|
UserAgent string `json:"user_agent"`
|
|
Errors []string `json:"errors,omitempty"`
|
|
Extra map[string]any `json:"extra,omitempty"`
|
|
}
|
|
|
|
func LoggingMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
requestID := uuid.New().String()
|
|
|
|
c.Set("request_id", requestID)
|
|
|
|
c.Next()
|
|
|
|
duration := time.Since(start)
|
|
|
|
userID, _ := c.Get("user_id")
|
|
userIDStr := ""
|
|
if uid, ok := userID.(uuid.UUID); ok {
|
|
userIDStr = uid.String()
|
|
}
|
|
|
|
var errors []string
|
|
for _, err := range c.Errors {
|
|
errors = append(errors, err.Error())
|
|
}
|
|
|
|
entry := RequestLogger{
|
|
RequestID: requestID,
|
|
Method: c.Request.Method,
|
|
Path: c.Request.URL.Path,
|
|
Status: c.Writer.Status(),
|
|
Duration: duration,
|
|
UserID: userIDStr,
|
|
ClientIP: c.ClientIP(),
|
|
UserAgent: c.Request.UserAgent(),
|
|
Errors: errors,
|
|
}
|
|
|
|
if logData, err := json.Marshal(entry); err == nil {
|
|
log.Println(string(logData))
|
|
} else {
|
|
log.Printf("failed to marshal log entry: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func RequestIDFromContext(c *gin.Context) string {
|
|
if rid, exists := c.Get("request_id"); exists {
|
|
if ridStr, ok := rid.(string); ok {
|
|
return ridStr
|
|
}
|
|
}
|
|
return ""
|
|
}
|