禁用特定Go-Gin路由的请求记录

toiithl6  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(166)

我有一堆路由,用gin.Default()启动gin(默认情况下启用所有路由的日志记录和恢复)。但有一条路(即。/health),每5秒ping一次。有什么简单的方法可以在不更改大量代码的情况下禁用该路由的请求日志记录?

func main() {
    // gin is initialized upstream in our internal framework
    // so I can't change this line easily.
    router := gin.Default()

    router.GET("/someGet", getting)
    router.POST("/somePost", posting)
    router.PUT("/somePut", putting)
    router.DELETE("/someDelete", deleting)
    // ... and more

    // Disable request logging for only this route. 
    // Note: I'm hoping that there's some parameter I can pass in here to do that
    route.GET("/health", health)

    router.Run()

}
icnyk63a

icnyk63a1#

@Paul Lam的解决方案有效!以下代码供参考:

router := gin. Default()

成为

router := gin.New()
    router.Use(
        gin.LoggerWithWriter(gin.DefaultWriter, "/pathsNotToLog/"),
        gin.Recovery(),
    )

github.com/gin-gonic/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection) /gin.go引用的gin.Default()定义

vc6uscn9

vc6uscn92#

gin.Logger()有一个更长的形式,带有args,可以接受列出不应该记录的路径的字符串的args,即gin.LoggerWithWriter(gin.DefaultWriter, "<NO LOG PATH 1>", ...)
我用baseService.GinEngine = gin.New()覆盖了基本结构体GinService,然后手动附加了gin.LoggerWithWriter(...)和gin.Recovery()中间件。
这招奏效了

mmvthczy

mmvthczy3#

还有一个gin.LoggerWithConfig中间件:

router.Use(gin.LoggerWithConfig(gin.LoggerConfig{SkipPaths: []string{"/static"}}))
type LoggerConfig struct {
    // Optional. Default value is gin.defaultLogFormatter
    Formatter LogFormatter

    // Output is a writer where logs are written.
    // Optional. Default value is gin.DefaultWriter.
    Output io.Writer

    // SkipPaths is a url path array which logs are not written.
    // Optional.
    SkipPaths []string
}

相关问题