Search code examples
javaspring-bootlogback

SpringBoot loggin request and response in the same line


We developed a Rest Api Backend with SpringBoot framework and RestControllers. Now, we have to generate a log (before send response), that contains: Request Headers - Request Body - Response Header - Response Body

Looking for an answer, we found some examples (using a filter or AOP), but all of these generate a log for request and an other log for response.

It is possibile to generate a single log? How?

Thank you!


Solution

  • You can achieve by implementing filter. You can override doFilter method and log after chain process. Example code below.

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        ContentCachingResponseWrapper responseWrapper =new ContentCachingResponseWrapper((HttpServletResponse) response);
        try {
            chain.doFilter(requestWrapper, responseWrapper);
        } finally {
            String requestBody=new String(requestWrapper.getContentAsByteArray(),requestWrapper.getCharacterEncoding());
            String responseBody=new String(responseWrapper.getContentAsByteArray(),responseWrapper.getCharacterEncoding());
            int statusCode = responseWrapper.getStatus();
            final String ip = requestWrapper.getRemoteAddr();
            final String requestUrl = requestWrapper.getRequestURL().toString();
            final String clientId = requestWrapper.getHeader("any-header");
            responseWrapper.copyBodyToResponse();
            // todo : here you can log any information which can extracted from request and response wrapper.
        }
    }