gin.logger with formatter code example
Example: gin.logger with formatter
type respBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w respBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
// LogRequest is a middleware to log each request
func LogRequest(Logger *logger.Logger, logResponse bool) gin.HandlerFunc {
return func(c *gin.Context) {
rbw := &respBodyWriter{
body: bytes.NewBufferString(""),
ResponseWriter: c.Writer,
}
c.Writer = rbw
start := time.Now()
ctxCpy := c.Copy()
c.Next()
latency := time.Now().Sub(start)
fields := make(map[string]interface{})
fields["requestData"] = parseRequestForm(ctxCpy)
if logResponse {
fields["responseData"] = rbw.body.String()
}
Logger.WithFields(fields).Infof("[Request] %v |%3d| %13v | %15s |%-7s %s",
start.Format("2006/01/02 - 15:04:05"),
c.Writer.Status(),
latency,
c.ClientIP(),
c.Request.Method,
c.Request.URL.Path,
)
}
}