当前位置:网站首页>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())
}
}
边栏推荐
- Teach you how to realize pynq-z2 bar code recognition
- 易周金融 | Q1手机银行活跃用户规模6.5亿;理财子公司布局新兴领域
- Make a ThreadLocal (source code) that everyone can understand
- AQS Abstract queue synchronizer
- Unity3d best practices: folder structure and source control
- Practice of constructing ten billion relationship knowledge map based on Nebula graph
- ReentrantLock、ReentrantReadWriteLock、StampedLock
- Pri3d: a representation learning method for 3D scene perception using inherent attributes of rgb-d data
- Cannot determine value type from string ‘<p>1</p>‘
- AI begets the moon, and thousands of miles share the literary heart
猜你喜欢

Unity3d best practices: folder structure and source control

Admixture usage document Cookbook

阅读别人的代码,是一种怎样的体验

基于 Nebula Graph 构建百亿关系知识图谱实践

Volatile and JMM

The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend

2022-2-16 learning the imitated Niuke project - Section 6 adding comments

Interview question: rendering 100000 data solutions

Teach you how to package and release the mofish Library

Practice of constructing ten billion relationship knowledge map based on Nebula graph
随机推荐
The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend
2022-2-15 learning the imitated Niuke project - Section 5 shows comments
Strong, weak, soft and virtual references of ThreadLocal
PostgreSQL 15新版本特性解读(含直播问答、PPT资料汇总)
Calcul de la confidentialité Fate - Prévisions hors ligne
Naacl 2022 | TAMT: search the transportable Bert subnet through downstream task independent mask training
Creation and use of static library (win10+vs2022
基于SSM的Web网页聊天室系统
反射学习总结
Resolve activity startup - lifecycle Perspective
Julia1.1 installation instructions
Vscode uses yapf auto format to set the maximum number of characters per line
Pri3d: a representation learning method for 3D scene perception using inherent attributes of rgb-d data
Redis 主从复制、哨兵模式、Cluster集群
Different perspectives
522. longest special sequence II / Sword finger offer II 101 Split equal sum subset
PR second training notes
Use of abortcontroller
Too many requests at once, and the database is in danger
I want to buy fixed income + products, but I don't know what its main investment is. Does anyone know?