본문 바로가기

Programming/Tip&Informaion

[go/gin] log에 request, response 출력하기

1. 로그 형식을 json 형태로 출력 (https://stackoverflow.com/a/73936927)

func jsonLoggerMiddleware() gin.HandlerFunc {
    return gin.LoggerWithFormatter(
        func(params gin.LogFormatterParams) string {
            log := make(map[string]interface{})

            log["status_code"] = params.StatusCode
            log["path"] = params.Path
            log["method"] = params.Method
            log["start_time"] = params.TimeStamp.Format("2006/01/02 - 15:04:05")
            log["remote_addr"] = params.ClientIP
            log["response_time"] = params.Latency.String()

            s, _ := json.Marshal(log)
            return string(s) + "\n"
        },
    )
}

 

2. 출력 가능 내용

https://github.com/gin-gonic/gin/blob/8763f33c65f7df8be5b9fe7504ab7fcf20abb41d/logger.go#L63

 

gin/logger.go at 8763f33c65f7df8be5b9fe7504ab7fcf20abb41d · gin-gonic/gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin. - ...

github.com

 

3. response body 출력

https://stackoverflow.com/a/38548555

 

How to log response body in gin

I need to log the response body in a middleware of gin, but I don't find how to get the response body. Can anyone help? I am using a middleware like this: func Logger() gin.HandlerFunc { ret...

stackoverflow.com

 

4. 근데 response body는 한 번 읽으면 다시 처리가 불가능해서 response body를 단순 c.Bind() 함수로 처리하고 있었으면 c.ShouldBindBodyWith() 함수로 변경해서 처리해야 body를 여러번 쓸 수 있어서 활용할 수 있음

https://pkg.go.dev/github.com/gin-gonic/gin#Context.ShouldBindBodyWith