mdoTomofumi Chiba
4/10/2024, 11:07:07 PM

Spring: Exception 発生時にリクエスト内容をエラーログする

ContentCachingRequestWrapper を使う。

@Slf4j
public class ApplicationFilter implements Filter {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
        var req = new ContentCachingRequestWrapper((HttpServletRequest) request);
        var res = (HttpServletResponse) response;
        try {
            chain.doFilter(req, res);
        } catch (Exception e) {
            var map = new HashMap<String, Object>();
            map.put("path", req.getServletPath());
            map.put("parameter", req.getParameterMap());
            map.put("body", new String(req.getContentAsByteArray(), req.getCharacterEncoding()));
            log.error("exception: " + objectMapper.writeValueAsString(map), e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
TweetBlueskyLike