First question is what type I should use in my entity for request and
response ( string, blob, etc)
It mainly depends on the database vendor and request/response length.
String may be limited for some vendors and blob is so required.
On the other hand, matching on blob is slower.
Another alternative is using a nosql format such as JSON.
Second question, how to get request,response and its controller name
to create the entity to save to database ?
There are really several ways.
You could take advantage of built-in Spring Boot http tracing features but it has a limitation : posted/received of request/responses are not available.
5.8. HTTP Tracing
HTTP Tracing can be enabled by providing a bean of type
HttpTraceRepository in your application’s configuration. For
convenience, Spring Boot offers an InMemoryHttpTraceRepository that
stores traces for the last 100 request-response exchanges, by default.
InMemoryHttpTraceRepository is limited compared to other tracing
solutions and we recommend using it only for development environments.
For production environments, use of a production-ready tracing or
observability solution, such as Zipkin or Spring Cloud Sleuth, is
recommended. Alternatively, create your own HttpTraceRepository that
meets your needs.
The httptrace endpoint can be used to obtain information about the
request-response exchanges that are stored in the HttpTraceRepository.
5.8.1. Custom HTTP tracing
To customize the items that are included in each trace, use the
management.trace.http.include configuration property. For advanced
customization, consider registering your own HttpExchangeTracer
implementation.
Alternatives are implementing a filter for requests/responses and log in it.
For example :
@Component
public class RequestResponseStoringFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
long start = System.currentTimeMillis();
try {
chain.doFilter(req, resp);
} finally {
// Measure elapsed time
long elapsed = System.currentTimeMillis() - start;
// store request data and store response data in a DB
.....
}
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
Lastly, is it possible to calculate response time (time spent in the
controller) of the controller ?
The way implement a Filter can do that as shown above.
The httptrace endpoint way provides that with the timeTaken
field.
FIY, here is the content of a HttpTrace instance :
HttpTrace.Principal getPrincipal()
HttpTrace.Request getRequest()
HttpTrace.Response getResponse()
HttpTrace.Session getSession()
Instant getTimestamp()
Long getTimeTaken()