You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.4 KiB
70 lines
1.4 KiB
package Middleware
|
|
|
|
import (
|
|
"dsData/Utils/ConfigUtil"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
"github.com/tracer0tong/kafkalogrus"
|
|
"time"
|
|
)
|
|
|
|
//转为东八区时间
|
|
type CSTFormatter struct {
|
|
logrus.Formatter
|
|
}
|
|
|
|
func (u CSTFormatter) Format(e *logrus.Entry) ([]byte, error) {
|
|
e.Time = e.Time.Local()
|
|
return u.Formatter.Format(e)
|
|
}
|
|
|
|
func init() {
|
|
var err error
|
|
var hook *kafkalogrus.KafkaLogrusHook
|
|
if hook, err = kafkalogrus.NewKafkaLogrusHook(
|
|
"kh",
|
|
logrus.AllLevels,
|
|
&logrus.JSONFormatter{},
|
|
[]string{ConfigUtil.KafkaAddress},
|
|
ConfigUtil.KafkaAccessLogTopic,
|
|
true, nil); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
//设置日志格式
|
|
logrus.SetFormatter(CSTFormatter{&logrus.JSONFormatter{}})
|
|
logrus.AddHook(hook)
|
|
}
|
|
|
|
// 日志记录到 Kafka
|
|
func LoggerToKafka() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 开始时间
|
|
startTime := time.Now().Local()
|
|
// 处理请求
|
|
c.Next()
|
|
// 结束时间
|
|
endTime := time.Now().Local()
|
|
// 执行时间
|
|
latencyTime := endTime.Sub(startTime)
|
|
// 请求方式
|
|
reqMethod := c.Request.Method
|
|
// 请求路由
|
|
reqUri := c.Request.RequestURI
|
|
// 状态码
|
|
statusCode := c.Writer.Status()
|
|
// 请求IP
|
|
clientIP := c.ClientIP()
|
|
|
|
// 日志格式
|
|
logrus.WithFields(logrus.Fields{
|
|
"status_code": statusCode,
|
|
"access_time": startTime,
|
|
"latency_time": latencyTime,
|
|
"client_ip": clientIP,
|
|
"req_method": reqMethod,
|
|
"req_uri": reqUri,
|
|
}).Info()
|
|
}
|
|
}
|