69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package core
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
|
"io/ioutil"
|
|
"log"
|
|
"path/filepath"
|
|
"time"
|
|
)
|
|
|
|
func SetupLogger() *lumberjack.Logger {
|
|
// 获取当前日期
|
|
now := time.Now()
|
|
month := now.Format("2006-01")
|
|
day := now.Format("2006-01-02")
|
|
|
|
// 日志文件路径
|
|
logFilePath := filepath.Join("./logs", month, day)
|
|
|
|
// 配置 lumberjack 日志轮转
|
|
logger := &lumberjack.Logger{
|
|
Filename: logFilePath,
|
|
MaxSize: 1, // 日志文件最大尺寸为100MB
|
|
MaxBackups: 30, // 最多保留30个备份文件
|
|
MaxAge: 30, // 日志文件最多保留30天
|
|
Compress: false, // 启用压缩
|
|
}
|
|
|
|
return logger
|
|
}
|
|
|
|
func LoggingMiddleware(logger *lumberjack.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 记录开始时间
|
|
startTime := time.Now()
|
|
|
|
// 获取请求方法
|
|
method := c.Request.Method
|
|
|
|
// 获取GET参数
|
|
getParams := c.Request.URL.Query()
|
|
|
|
// 获取其他请求方法的参数
|
|
var bodyBytes []byte
|
|
if c.Request.Body != nil {
|
|
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
|
|
}
|
|
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // 还原请求Body
|
|
|
|
// 打印日志
|
|
logEntry := fmt.Sprintf("Start: %s, Method: %s, URL: %s, GET params: %v, Body: %s",
|
|
startTime.Format(time.RFC3339), method, c.Request.URL, getParams, string(bodyBytes))
|
|
log.SetOutput(logger)
|
|
log.Println(logEntry)
|
|
|
|
// 处理请求
|
|
c.Next()
|
|
|
|
// 记录结束时间
|
|
endTime := time.Now()
|
|
logEntry = fmt.Sprintf("End: %s, Method: %s, URL: %s, Status: %d, Latency: %s",
|
|
endTime.Format(time.RFC3339), method, c.Request.URL, c.Writer.Status(), endTime.Sub(startTime))
|
|
log.Println(logEntry)
|
|
}
|
|
}
|