package middleware import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/phuslu/log" ) // LogMiddleware is an middleware to log requests to phuslu/log and catches panics func LogMiddleware(c *gin.Context) { var xid log.XID var tmp interface{} var exists bool if tmp, exists = c.Get("xid"); !exists { xid = log.NewXIDWithTime(time.Now().UnixNano()) c.Set("xid", xid) } else { xid = tmp.(log.XID) } defer func() { var entry = log.Info() int := recover() if int != nil { err := int.(error) c.Header("requestid", xid.String()) c.AbortWithStatus(http.StatusInternalServerError) entry = log.Error().Err(err).Int("statuscode", 500) } else { statuscode := c.Writer.Status() if statuscode >= 400 { entry = log.Error() } entry = entry.Int("statuscode", statuscode) } entry.Int64("goroutine", log.Goid()).Xid("ID", xid).Msg("Request") }() c.Next() }