当前位置:网站首页>Gin general logging Middleware
Gin general logging Middleware
2022-06-27 15:09:00 【dz45693】
main.go
package main
import (
"demo/gindemo/middleware"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// 1. Create route
r := gin.Default()
r.Use(middleware.Logger())
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
r.POST("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, "hello World!")
})
r.Run(":8000")
}
logger.go
package middleware
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"time"
)
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)
}
func (w BodyLogWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
// Print log
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
/*
var buf bytes.Buffer
tee := io.TeeReader(c.Request.Body, &buf)
requestBody, _ := ioutil.ReadAll(tee)
c.Request.Body = ioutil.NopCloser(&buf)
*/
requestBody, _ := c.GetRawData()
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
bodyLogWriter := &BodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = bodyLogWriter
start := time.Now()
//handler
c.Next()
//log
end := time.Now()
responseBody := bodyLogWriter.body.String()
logField := map[string]interface{}{
"uri": c.Request.URL.Path,
"raw_query": c.Request.URL.RawQuery,
"start_timestamp": start.Format("2006-01-02 15:04:05"),
"end_timestamp": end.Format("2006-01-02 15:04:05"),
"server_name": c.Request.Host,
"remote_addr": c.ClientIP(),
"proto": c.Request.Proto,
"referer": c.Request.Referer(),
"request_method": c.Request.Method,
"response_time": end.Sub(start).Milliseconds(), // millisecond
"content_type": c.Request.Header.Get("Content-Type"),
"status": c.Writer.Status(),
"user_agent": c.Request.UserAgent(),
//"trace_id": c.Writer.Header().Get("X-Request-Trace-Id"),
"request_body": string(requestBody),
"response_body": responseBody,
"response_err": c.Errors.Last(),
}
//jsonByte, _ := json.MarshalIndent(logField, "", "\t")
// fmt.Print(string(jsonByte))
bf2 := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bf2)
jsonEncoder.SetEscapeHTML(false)
jsonEncoder.SetIndent("","\t")
jsonEncoder.Encode(logField)
fmt.Println(bf2.String())
}
}
边栏推荐
- Leetcode 724. 寻找数组的中心下标(可以,一次过)
- What are the operating modes of the live app? What mode should we choose?
- QT 如何在背景图中将部分区域设置为透明
- AQS Abstract queue synchronizer
- Privacy computing fat offline prediction
- ThreadLocal之强、弱、软、虚引用
- Elegant custom ThreadPoolExecutor thread pool
- About the meaning of the first two $symbols of SAP ui5 parameter $$updategroupid
- Design and implementation of food recipe and ingredients website based on vue+node+mysql
- At a time of oversupply of chips, China, the largest importer, continued to reduce imports, and the United States panicked
猜你喜欢
阅读别人的代码,是一种怎样的体验
What are the operating modes of the live app? What mode should we choose?
Semaphore of thread synchronization
Volatile and JMM
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
Creation and use of static library (win10+vs2022
2022-2-16 learning the imitated Niuke project - Section 6 adding comments
Référence forte, faible, douce et virtuelle de threadlocal
Computer screen splitting method
做一篇人人能搞懂的ThreadLocal(源码)
随机推荐
June 27, 2022 Daily: swin transformer, Vit authors and others said: a good basic model is the simple pursuit of CV researchers
【微服务|Sentinel】热点规则|授权规则|集群流控|机器列表
522. 最长特殊序列 II / 剑指 Offer II 101. 分割等和子集
Why can't the start method be called repeatedly? But the run method can?
Calcul de la confidentialité Fate - Prévisions hors ligne
All you want to know about large screen visualization is here
AutoCAD - line width setting
2022-2-15 learning the imitated Niuke project - Section 5 shows comments
2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
R language triple becomes matrix matrix becomes triple
What are the operating modes of the live app? What mode should we choose?
Longest substring without repeated characters (Sword finger offer 48)
Programming skills: script scheduling
Reflection learning summary
How is the London Silver point difference calculated
R language objects are stored in JSON
How to change a matrix into a triple in R language (i.e. three columns: row, col, value)
What kind of experience is it to read other people's code
固收+产品有什么特点?
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)