当前位置:网站首页>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())
}
}
边栏推荐
- R language triple becomes matrix matrix becomes triple
- 数学建模经验分享:国赛美赛对比/选题参考/常用技巧
- 巧用redis实现点赞功能,它不比mysql香吗?
- Integration of entry-level SSM framework based on XML configuration file
- LVI: feature extraction and sorting of lidar subsystem
- 图书管理系统
- 2022-2-16 learning the imitated Niuke project - Section 6 adding comments
- AQS抽象队列同步器
- 隐私计算FATE-离线预测
- Notes learning summary
猜你喜欢

Privacy computing fat offline prediction

Atomic operation class

Computer screen splitting method

ReentrantLock、ReentrantReadWriteLock、StampedLock

Pycharm安装与设置
![[digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)](/img/80/28d53985d56d64ca721b26e846c667.jpg)
[digital signal processing] discrete time signal (analog signal, discrete time signal, digital signal | sampling leads to time discrete | quantization leads to amplitude discrete)

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

How QT sets some areas to be transparent in the background image

ReentrantLock、ReentrantReadWriteLock、StampedLock

What is the London Silver unit
随机推荐
R language objects are stored in JSON
QT 如何在背景图中将部分区域设置为透明
Admixture usage document Cookbook
Leetcode 724. Find the central subscript of the array (yes, once)
Volatile and JMM
Creation and use of static library (win10+vs2022
June 27, 2022 Daily: swin transformer, Vit authors and others said: a good basic model is the simple pursuit of CV researchers
SQL parsing practice of Pisa proxy
基于SSM的Web网页聊天室系统
16 -- 删除无效的括号
Pisa-Proxy 之 SQL 解析实践
Knowledge map model
[advanced MySQL] MTS master-slave synchronization principle and Practice Guide (7)
Hyperledger Fabric 2. X custom smart contract
Li Kou's 81st biweekly match
ReentrantLock、ReentrantReadWriteLock、StampedLock
[microservices sentinel] hotspot rules | authorization rules | cluster flow control | machine list
How to change a matrix into a triple in R language (i.e. three columns: row, col, value)
How QT sets some areas to be transparent in the background image
The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend