Files
Rogee 7fcabe0225
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
first commit
2025-09-28 10:05:07 +08:00

59 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}