Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.8 kB
2
Indexable
Never
package pl.inpost.parcellogisticstatusprovider.application.log;

import static org.apache.commons.lang3.StringUtils.containsAny;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

@RequiredArgsConstructor
@Component
public class LoggingFilter extends OncePerRequestFilter {

    private final Logger log;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if (containsAny(request.getServletPath(), "/swagger", "/api-docs", "/favicon", "/health")) {
            return true;
        }
        return super.shouldNotFilter(request);
    }


    @Override
    protected void doFilterInternal(final @NonNull HttpServletRequest request, final @NonNull HttpServletResponse response,
                                    final FilterChain filterChain)
        throws ServletException, IOException {
        long startTime = System.currentTimeMillis();

        CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request);
        ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response);

        logRequest(wrappedRequest);
        try {
            filterChain.doFilter(wrappedRequest, wrappedResponse);
        } finally {
            logResponse(wrappedResponse, System.currentTimeMillis() - startTime, wrappedRequest.getMethod() + " " + wrappedRequest.getRequestURI());
            wrappedResponse.copyBodyToResponse();
        }
    }

    private void logRequest(final HttpServletRequest request) throws IOException {
        CachedBodyHttpServletRequest wrapper = WebUtils.getNativeRequest(request, CachedBodyHttpServletRequest.class);
        log.request(wrapper.getMethod(), wrapper.getRequestURI(), wrapper.getQueryString(), RequestLoggingHelper.getRequestBody(wrapper),
            RequestLoggingHelper.getRequestHeaders(wrapper));
    }

    private void logResponse(final HttpServletResponse response, long executionTime, String request) throws IOException {
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        log.response(executionTime, RequestLoggingHelper.getResponseBody(wrapper), wrapper.getStatus(),
            RequestLoggingHelper.getResponseHeaders(wrapper), request);
        wrapper.copyBodyToResponse();
    }
}