Search code examples
grailsspring-bootgrails-3.0

How to log request and response (headers+body) using Grails 3?


I am looking for ways to log the incoming request and returned response (headers+body) in a Grails 3 application. Grails has the notion of interceptors, but in these interceptors I am unable to read the body as the body can only be read once. So if i do this in the interceptor then the normal controller logic fails with an error indicating that the stream is already closed.

I also tried to find ways on how this can be done using SpringBoot as Grails is actually based on SpringBoot.

Any hints on how this can be done in a Grails 3 application?


Solution

  • I suggest the following approach (haven't found anything available for spring-boot when I needed a similar functionality, so I've decided to roll my own):

    • Implement a HttpServletRequestWrapper which will copy the bytes as the InputStream is being consumed so you can re-read the request body multiple times

    • Implement and register a Filter which will wrap the http request on the way in and log the complete request/response after the request is consumed and the response is produced by the endpoint

    Nice bonus is that you can log both request and response in one logging statement, keeping them together in the logfile.