Paul Lam
Paul Lam

Reputation: 1819

Disable request logging for a particular Go-Gin route

I have a bunch of routes and start off gin with gin.Default() (enabling logging and recovery for all routes by default). But there is one route (i.e. /health) that gets pinged every 5 seconds. What's a straightforward way to disable request logging for that one route without changing much of the code?

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()

}

Upvotes: 16

Views: 13960

Answers (3)

Calli Gross
Calli Gross

Reputation: 285

There is also a gin.LoggerWithConfig middleware:

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
}

Upvotes: 8

Kanak Singhal
Kanak Singhal

Reputation: 3312

@Paul Lam's solution works! heres the code for reference:

    router := gin. Default()

Becomes

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

gin.Default() definition referred from github.com/gin-gonic/[email protected]/gin.go

Upvotes: 22

Paul Lam
Paul Lam

Reputation: 1819

gin.Logger() has a longer form with args that can take in args of strings listing paths that should not be logged, i.e. gin.LoggerWithWriter(gin.DefaultWriter, "<NO LOG PATH 1>", ...).

I overwrote the base struct GinService with, baseService.GinEngine = gin.New() and then attached gin.LoggerWithWriter(...) and gin.Recovery() middlewares manually.

That did the trick.

Upvotes: 15

Related Questions