Skip to content

Commit

Permalink
Merge pull request #127 from taosdata/fix/TD-30968
Browse files Browse the repository at this point in the history
add gin log to log file
  • Loading branch information
sheyanjie-qq authored Jul 15, 2024
2 parents 4bc9d8b + 7d0fd19 commit 4ac3a44
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
49 changes: 49 additions & 0 deletions infrastructure/log/web.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package log

import (
"time"

"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)

func GinLog() gin.HandlerFunc {
logger := GetLogger("web")

return func(c *gin.Context) {
startTime := time.Now()
c.Next()
endTime := time.Now()
latencyTime := endTime.Sub(startTime)
reqMethod := c.Request.Method
reqUri := c.Request.RequestURI
statusCode := c.Writer.Status()
clientIP := c.ClientIP()

logger.Infof("[GIN] %v | %3d | %13v | %15s | %-7s %s",
endTime.Format("2006/01/02 - 15:04:05"),
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
}
}

type recoverLog struct {
logger logrus.FieldLogger
}

func (r *recoverLog) Write(p []byte) (n int, err error) {
r.logger.Errorln(string(p))
return len(p), nil
}

func GinRecoverLog() gin.HandlerFunc {
logger := GetLogger("web")
return func(c *gin.Context) {
writer := &recoverLog{logger: logger}
gin.RecoveryWithWriter(writer)(c)
}
}
2 changes: 2 additions & 0 deletions system/program.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ func Init() *http.Server {
}

router := web.CreateRouter(conf.Debug, &conf.Cors, false)
router.Use(log.GinLog())
router.Use(log.GinRecoverLog())

reporter := api.NewReporter(conf)
reporter.Init(router)
Expand Down

0 comments on commit 4ac3a44

Please sign in to comment.