67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
//
|
|
// access_log.go
|
|
// Copyright (C) 2022 tiglog <me@tiglog.com>
|
|
//
|
|
// Distributed under terms of the MIT license.
|
|
//
|
|
|
|
package middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"io/ioutil"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"git.hexq.cn/tiglog/golib/logger"
|
|
)
|
|
|
|
func GinLogger() gin.HandlerFunc {
|
|
log := logger.Access()
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
raw := c.Request.URL.RawQuery
|
|
latency := time.Since(start)
|
|
|
|
// 处理请求
|
|
c.Next()
|
|
|
|
clientIP := c.ClientIP()
|
|
method := c.Request.Method
|
|
statusCode := c.Writer.Status()
|
|
|
|
comment := c.Errors.ByType(gin.ErrorTypePrivate).String()
|
|
|
|
if raw != "" {
|
|
path = path + "?" + raw
|
|
}
|
|
|
|
l := log.Log()
|
|
if comment != "" {
|
|
l = log.Error()
|
|
}
|
|
var buf bytes.Buffer
|
|
tee := io.TeeReader(c.Request.Body, &buf)
|
|
requestBody, _ := ioutil.ReadAll(tee)
|
|
c.Request.Body = ioutil.NopCloser(&buf)
|
|
|
|
l.
|
|
Str("proto", c.Request.Proto).
|
|
Str("server_name", c.Request.Host).
|
|
Str("content_type", c.Request.Header.Get("Content-Type")).
|
|
Str("user_agent", c.Request.UserAgent()).
|
|
Str("method", method).
|
|
Str("path", path).
|
|
Int("status_code", statusCode).
|
|
Str("client_ip", clientIP).
|
|
Dur("latency", latency)
|
|
|
|
if gin.IsDebugging() {
|
|
l.Str("content", string(requestBody))
|
|
}
|
|
l.Msg(comment)
|
|
}
|
|
}
|