当前位置:网站首页>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())
}
}
边栏推荐
- 优雅的自定义 ThreadPoolExecutor 线程池
- [digital signal processing] discrete time signal (discrete time signal knowledge points | signal definition | signal classification | classification according to certainty | classification according t
- A brief analysis of the differences between domestic and foreign e-commerce
- 522. 最长特殊序列 II / 剑指 Offer II 101. 分割等和子集
- Elegant custom ThreadPoolExecutor thread pool
- Nvidia Deepstream 运行延迟,卡顿,死机处理办法
- Je veux acheter des produits à revenu fixe + mais je ne sais pas quels sont ses principaux investissements.
- Redis 主从复制、哨兵模式、Cluster集群
- Hyperledger Fabric 2. X custom smart contract
- February 16, 2022 freetsdb compilation and operation
猜你喜欢

AutoCAD - line width setting

Integration of entry-level SSM framework based on XML configuration file

Pycharm安装与设置

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

CAS之比较并交换

volatile与JMM

隐私计算FATE-离线预测
![[WUSTCTF2020]girlfriend](/img/a8/33fe5feb7bcbb73ba26a94d226cc4d.png)
[WUSTCTF2020]girlfriend

Great God developed the new H5 version of arXiv, saying goodbye to formula typography errors in one step, and the mobile phone can easily read literature

ReentrantLock、ReentrantReadWriteLock、StampedLock
随机推荐
基于Vue+Node+MySQL的美食菜谱食材网站设计与实现
Design skills of main function of Blue Bridge Cup single chip microcomputer
How is the London Silver point difference calculated
隐私计算FATE-离线预测
NLP - monocleaner
隱私計算FATE-離線預測
June 27, 2022 Daily: swin transformer, Vit authors and others said: a good basic model is the simple pursuit of CV researchers
Google tool splits by specified length
[advanced MySQL] MTS master-slave synchronization principle and Practice Guide (7)
2022-06-27日报:Swin Transformer、ViT作者等共话:好的基础模型是CV研究者的朴素追求
简析国内外电商的区别
Web chat room system based on SSM
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
Multithreading Basics (III)
机械硬盘和ssd固态硬盘的原理对比分析
ReentrantLock、ReentrantReadWriteLock、StampedLock
R language triple becomes matrix matrix becomes triple
Interpretation of new version features of PostgreSQL 15 (including live Q & A and PPT data summary)
Teach you how to realize pynq-z2 bar code recognition
優雅的自定義 ThreadPoolExecutor 線程池