Solución:
Puedes extender RequestBodyAdviceAdapter
e implementar el método afterBodyRead
:
@ControllerAdvice
public MyRequestBodyAdviceAdapter extends RequestBodyAdviceAdapter {
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
// write body -your input dto- to logs or database or whatever
return body;
}
}
RequestBodyAdvice viene en pre-setp la cadena de solicitud antes de la HandlerInterceptor
. es exactamente después de que el flujo de entrada de la solicitud http se convierta en su objeto.
Por lo que sé, RequestBody
y ResponseBody
solo se puede leer una vez. Por tanto, no deberías leerlos en un Interceptor
. Aquí tienes una explicación.
Como dijeron otros, no puede leer el flujo de entrada de solicitud o el flujo de salida de respuesta más de una vez, pero puede usar Filtros para reemplazar los objetos de solicitud y respuesta originales por otros envueltos. De esta manera, puede implementar su contenedor y almacenar en búfer la carga útil, de esta manera puede usarlo cuantas veces desee.
Aquí un repositorio con el código de trabajo: https://github.com/glaudiston/spring-boot-rest-payload-logging
Solo haz un mvn clean install
en él y sea feliz.
$ java -jar target/rest-service-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _
( ( )___ | '_ | '_| | '_ / _` |
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |___, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.2.RELEASE)
2020-01-24 13:06:07.297 INFO 918 --- [ main] c.e.restservice.RestServiceApplication : Starting RestServiceApplication v0.0.1-SNAPSHOT on ca275nt with PID 918 (/home/ggs/src/spring-boot-rest-payload-logging/target/rest-service-0.0.1-SNAPSHOT.jar started by ggs
in /home/ggs/src/spring-boot-rest-payload-logging)
2020-01-24 13:06:07.301 INFO 918 --- [ main] c.e.restservice.RestServiceApplication : No active profile set, falling back to default profiles: default
2020-01-24 13:06:08.331 INFO 918 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-01-24 13:06:08.348 INFO 918 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-01-24 13:06:08.348 INFO 918 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-01-24 13:06:08.410 INFO 918 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-01-24 13:06:08.410 INFO 918 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1044 ms
2020-01-24 13:06:08.627 INFO 918 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-01-24 13:06:08.787 INFO 918 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-01-24 13:06:08.791 INFO 918 --- [ main] c.e.restservice.RestServiceApplication : Started RestServiceApplication in 1.928 seconds (JVM running for 2.319)
2020-01-24 13:06:11.014 INFO 918 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-24 13:06:11.014 INFO 918 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-01-24 13:06:11.022 INFO 918 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2020-01-24 13:06:11 [] INFO RequestFilter:23 - doFilter, parsing request
2020-01-24 13:06:11 [] INFO LogApiInterceptor:64 - Request Method: POST
2020-01-24 13:06:11 [] INFO LogApiInterceptor:65 - Request Headers:
2020-01-24 13:06:11 [] INFO LogApiInterceptor:66 - host:localhost:8080
user-agent:curl/7.64.0
accept:*/*
content-length:32
content-type:application/x-www-form-urlencoded
2020-01-24 13:06:11 [] INFO LogApiInterceptor:67 - Request body:
2020-01-24 13:06:11 [] INFO LogApiInterceptor:68 - testdata=123456789&test2=9876543
2020-01-24 13:06:11 [] INFO LogApiInterceptor:75 - Response Status: 200
2020-01-24 13:06:11 [] INFO LogApiInterceptor:76 - Response Headers:
2020-01-24 13:06:11 [] INFO LogApiInterceptor:77 -
2020-01-24 13:06:11 [] INFO LogApiInterceptor:78 - Response body:
2020-01-24 13:06:11 [] INFO LogApiInterceptor:84 - {"id":1,"content":"Hello, World!"}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────
$ curl -X POST --data "testdata=123456789&test2=9876543" http://localhost:8080/greeting
{"id":1,"content":"Hello, World!"}