Golang logging http responses (in addition to requests)

前端 未结 3 1643
悲&欢浪女
悲&欢浪女 2020-12-19 05:29

I am using Go and the Gorilla web toolkit\'s mux and handler packages to build a complex application, part of which requires a http server. Gorilla\'s mux and handler packa

3条回答
  •  不知归路
    2020-12-19 06:02

    edit sorry, I didn't notice your mention of gorilla-mux, I have only tried this with gin, but if it uses middlewares this should still work.


    the trick is, c.Next() in a middleware blocks until all subsequent middlewares return. Here's a logrus solution. Put this as your first middleware:

    func Logrus(logger *logrus.Logger) gin.HandlerFunc {
        return func(c *gin.Context) {
            start := time.Now().UTC()
            path := c.Request.URL.Path
            c.Next()
            end := time.Now().UTC()
            latency := end.Sub(start)
            logger.WithFields(logrus.Fields{
                "status":     c.Writer.Status(),
                "method":     c.Request.Method,
                "path":       path,
                "ip":         c.ClientIP(),
                "duration":   latency,
                "user_agent": c.Request.UserAgent(),
            }).Info()
        }
    }
    GinEngine.Use(Logrus(logrus.StandardLogger()))
    

提交回复
热议问题