Spring boot request header 정보 출력하기

2024. 12. 13. 21:01Java/Spring Boot

Filter 사용

415 에러 등이 발생했을 때, header값이 어떤 값이 들어왔는지 확인이 안될 때 사용하면 좋을 것 같음

body는 한번 사용되면, 사라지기 때문에 ContentCachingRequestWrapper wrappedRequest로 받아서 별도 처리해야 함

정상적으로 처리되면 body가 출력되지만, 에러가 발생하는 경우(415 등) body는 null값이 출력됨

@Slf4j
@Component
public class RequestLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            // Wrap the request to enable caching of the body
            ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(httpServletRequest);

            // Log Headers
            log.info("Request Headers:");
            Enumeration<String> headerNames = wrappedRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                log.info("{}: {}", headerName, wrappedRequest.getHeader(headerName));
            }

            // Proceed with the filter chain
            chain.doFilter(wrappedRequest, response);

            // Log Body after the chain (so controllers can process it first)
            String requestBody = getRequestBody(wrappedRequest);
            log.info("Request Body: {}", requestBody);
        } else {
            chain.doFilter(request, response);
        }
    }

    private String getRequestBody(ContentCachingRequestWrapper request) {
        byte[] content = request.getContentAsByteArray();
        if (content.length > 0) {
            try {
                return new String(content, request.getCharacterEncoding());
            } catch (IOException e) {
                log.error("Error reading request body", e);
            }
        }
        return null;
    }
}

@RequestHeader 사용

@RestController
@RequestMapping("/api")
public class HeaderController {

    @GetMapping("/print-headers")
    public ResponseEntity<String> printHeaders(@RequestHeader Map<String, String> headers) {
        headers.forEach((key, value) -> {
            System.out.println("Header Name: " + key + " | Header Value: " + value);
        });
        return ResponseEntity.ok("Headers printed in console");
    }
}