123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- package logger
- import (
- "bytes"
- "github.com/gin-gonic/gin"
- "github.com/sirupsen/logrus"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- )
- func LogToFile() gin.HandlerFunc {
- return func(ctx *gin.Context) {
-
- blw := &bodyLogWriter{
- body: bytes.NewBufferString(""),
- ResponseWriter: ctx.Writer,
- }
- ctx.Writer = blw
-
- startTime := time.Now()
-
- reqMethod := ctx.Request.Method
-
- reqUri := ctx.Request.RequestURI
-
- if strings.Contains(reqUri, "/api/blade-log/usual") {
- ctx.Next()
- return
- }
-
- request := getRequestBody(ctx)
-
- clientIP := ctx.ClientIP()
-
- ctx.Next()
-
- endTime := time.Now()
-
- latencyTime := endTime.Sub(startTime)
-
- statusCode := ctx.Writer.Status()
-
- response := blw.body.String()
-
- Logger.WithFields(logrus.Fields{
- "status_code": statusCode,
- "latency_time": latencyTime,
- "client_ip": clientIP,
- "req_method": reqMethod,
- "request": request,
- "response": response,
- "req_uri": reqUri,
- "t": time.Now().UnixMilli(),
- }).Info()
- }
- }
- func getRequestBody(ctx *gin.Context) interface{} {
- if strings.Contains(ctx.ContentType(), "multipart/form-data") {
- return "multipart"
- }
- switch ctx.Request.Method {
- case http.MethodGet:
- fallthrough
- case http.MethodDelete:
- return ctx.Request.URL.Query()
- case http.MethodPost:
- fallthrough
- case http.MethodPut:
- fallthrough
- case http.MethodPatch:
- var bodyBytes []byte
- bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
- if err != nil {
- return nil
- }
- ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
- return string(bodyBytes)
- }
- return nil
- }
- type bodyLogWriter struct {
- gin.ResponseWriter
- body *bytes.Buffer
- }
- func (w bodyLogWriter) Write(b []byte) (int, error) {
- w.body.Write(b)
- return w.ResponseWriter.Write(b)
- }
|