Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable request logging for a particular Go-Gin route

Tags:

go-gin

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

}
like image 232
Paul Lam Avatar asked Feb 14 '18 05:02

Paul Lam


People also ask

What is Gin Default ()?

gin. Default() creates a Gin router with default middleware: logger and recovery middleware. Next, we make a handler using router. GET(path, handle) , where path is the relative path,​ and handle is the handler function that takes *gin. Context as an argument.

What is C * Gin context?

Returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string. func SomeHandler(c *gin. Context) { key := c. PostForm("key", "default value")

Should I bind JSON Gin?

What is Gin binding? Gin binding is an awesome de-serialization library. It supports JSON, XML, query parameter, and more out of the box and comes with a built-in validation framework. Gin bindings are used to serialize JSON, XML, path parameters, form data, etc. to structs and maps.

What is Gin recovery?

In gin-gonic you can use gin. Recover() middleware that helps your application to recover from panic. You can use instantiation via gin.New() or via gin.Default() (it's already included) handlers := gin.New() handlers.Use(gin.Recovery())


1 Answers

@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

like image 73
Kanak Singhal Avatar answered Sep 20 '22 12:09

Kanak Singhal