first commit
Some checks failed
CI/CD Pipeline / Test (push) Failing after 22m19s
CI/CD Pipeline / Security Scan (push) Failing after 5m57s
CI/CD Pipeline / Build (amd64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (amd64, linux) (push) Has been skipped
CI/CD Pipeline / Build (amd64, windows) (push) Has been skipped
CI/CD Pipeline / Build (arm64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (arm64, linux) (push) Has been skipped
CI/CD Pipeline / Build Docker Image (push) Has been skipped
CI/CD Pipeline / Create Release (push) Has been skipped
Some checks failed
CI/CD Pipeline / Test (push) Failing after 22m19s
CI/CD Pipeline / Security Scan (push) Failing after 5m57s
CI/CD Pipeline / Build (amd64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (amd64, linux) (push) Has been skipped
CI/CD Pipeline / Build (amd64, windows) (push) Has been skipped
CI/CD Pipeline / Build (arm64, darwin) (push) Has been skipped
CI/CD Pipeline / Build (arm64, linux) (push) Has been skipped
CI/CD Pipeline / Build Docker Image (push) Has been skipped
CI/CD Pipeline / Create Release (push) Has been skipped
This commit is contained in:
59
internal/middleware/logging.go
Normal file
59
internal/middleware/logging.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/subconverter-go/internal/logging"
|
||||
)
|
||||
|
||||
// SetupLogging 设置日志中间件
|
||||
// 记录所有HTTP请求的详细信息
|
||||
func SetupLogging(logger *logging.Logger) fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
start := time.Now()
|
||||
|
||||
// 处理请求
|
||||
err := c.Next()
|
||||
|
||||
// 计算请求耗时
|
||||
duration := time.Since(start)
|
||||
|
||||
// 记录请求日志
|
||||
logger.WithFields(map[string]interface{}{
|
||||
"method": c.Method(),
|
||||
"path": c.Path(),
|
||||
"ip": c.IP(),
|
||||
"user_agent": c.Get("User-Agent"),
|
||||
"status": c.Response().StatusCode(),
|
||||
"duration": duration.Milliseconds(),
|
||||
"size": len(c.Response().Body()),
|
||||
}).Infof("HTTP %s %s - %d (%v)", c.Method(), c.Path(), c.Response().StatusCode(), duration)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// SetupRequestID 设置请求ID中间件
|
||||
// 为每个请求生成唯一ID,便于追踪和调试
|
||||
func SetupRequestID() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// 生成请求ID
|
||||
requestID := generateRequestID()
|
||||
|
||||
// 设置到响应头
|
||||
c.Set("X-Request-ID", requestID)
|
||||
|
||||
// 存储到上下文
|
||||
c.Locals("requestID", requestID)
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// generateRequestID 生成请求ID
|
||||
func generateRequestID() string {
|
||||
// 使用时间戳和随机数生成唯一ID
|
||||
return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().Nanosecond()%1000000)
|
||||
}
|
||||
Reference in New Issue
Block a user