[英]log request body string in RestController ExceptionHandler
在 RestController 的 @ExceptionHandler 中记录请求正文字符串。
默认情况下,当请求无效 json 时,springboot 会抛出一个HttpMessageNotReadableException
,但消息很笼统,不包括具体的请求正文。 这使得调查变得困难。 另一方面,我可以使用过滤器记录每个请求字符串,但是这样日志将被太多成功的日志淹没。 我只想在请求无效时记录它。 我真正想要的是在@ExceptionHandler
中我会得到那个字符串(以前在某个地方)并记录为错误。
为了说明问题,我在 github 中创建了一个演示项目。
@RestController
public class GreetController {
protected static final Logger log = LogManager.getLogger();
@PostMapping("/")
public String greet(@RequestBody final WelcomeMessage msg) {
// if controller successfully returned (valid request),
// then don't want any request body logged
return "Hello " + msg.from;
}
@ExceptionHandler({HttpMessageNotReadableException.class})
public String addStudent(HttpMessageNotReadableException e) {
// this is what I really want!
log.error("{the request body string got somewhere, such as Filters }");
return "greeting from @ExceptionHandler";
}
}
有效请求curl -H "Content-Type: application/json" http://localhost:8080 --data '{"from":"jim","message":"nice to meet you!"}'
无效请求(无效 json) curl -H "Content-Type: application/json" http://localhost:8080 --data '{"from":"jim","message""nice to meet you!"}'
我曾经尝试过HandlerInterceptor
但会收到一些错误,例如
'java.lang.IllegalStateException: 在 getReader() 已经为当前请求调用后无法调用 getInputStream()'。
经过一番搜索1 2 ,我决定将Filter
与ContentCachingRequestWrapper
一起使用。
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
ContentCachingRequestWrapper cachedRequest = new ContentCachingRequestWrapper(httpServletRequest);
chain.doFilter(cachedRequest, response);
String requestBody = IOUtils.toString(cachedRequest.getContentAsByteArray(), cachedRequest.getCharacterEncoding());
log.info(requestBody);
}
此代码运行良好,只是日志位于RestController
之后。 如果我更改顺序:
String requestBody = IOUtils.toString(cachedRequest.getReader());
log.info(requestBody);
chain.doFilter(cachedRequest, response);
适用于无效请求,但当请求有效时,出现以下异常:
com.example.demo.GreetController:缺少所需的请求正文:公共 java.lang.String com.example.demo.GreetController.example.demo.com。
我还尝试了getContentAsByteArray
、 getInputStream
和getReader
方法,因为一些教程说框架会检查特定的方法调用。
CommonsRequestLoggingFilter
的建议尝试了 CommonsRequestLoggingFilter。 迪南。
但一切都是徒劳的。
现在我有点困惑。 当请求有效和无效时,谁能解释RestController
和Filter
的执行顺序? 有没有更简单的方法(更少的代码)来实现我的最终目标? 谢谢!
我正在使用springboot 2.6.3,jdk11。
创建一个过滤器,将您的请求包装在ContentCachingRequestWrapper
中(仅此而已)。
在您的异常处理方法中使用HttpServletRequest
作为参数作为参数
检查ContentCachingRequestWrapper
的实例是否
使用getContentAsByteArray
获取内容。
像这样的东西。
public class CachingFilter extends OncePerRequestFilter {
protected abstract void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(new ContentCachingRequestWrapper(request), new ContentCachingResponseWrapper(response));
}
注意:我也包装了响应,以防万一您也想要。
现在,在您的异常处理方法中,使用HttpServletRequest
作为参数并利用它对您有利。
@ExceptionHandler({HttpMessageNotReadableException.class})
public String addStudent(HttpMessageNotReadableException e, HttpServletRequest req) {
if (req instanceof ContentCachingRequestWrapper) {
ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) req;
log.error(new String(wrapper.getContentAsByteArray()));
}
return "greeting from @ExceptionHandler";
}
可能是多个过滤器向HttpServletRequest
添加了一个包装器,因此您可能需要遍历这些包装器,您也可以使用它
private Optional<ContentCachingRequestWrapper> findWrapper(ServletRequest req) {
ServletRequest reqToUse = req;
while (reqToUse instanceof ServletRequestWrapper) {
if (reqToUse instanceof ContentCachingRequestWrapper) {
return Optional.of((ContentCachingRequestWrapper) reqToUse);
}
reqToUse = ((ServletRequestWrapper) reqToUse).getRequest();
}
return Optional.empty();
}
你的异常处理程序看起来像这样
@ExceptionHandler({HttpMessageNotReadableException.class})
public String addStudent(HttpMessageNotReadableException e, HttpServletRequest req) {
Optional<ContentCachingRequestWrapper) wrapper = findWrapper(req);
wrapper.ifPresent(it -> log.error(new String(it.getContentAsByteArray())));
return "greeting from @ExceptionHandler";
}
但这可能取决于您的过滤器顺序以及是否有多个过滤器添加包装器。
在@M.Deinum 的评论之后,我解决了并希望对其他人有用:
public class MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
ContentCachingRequestWrapper cachedRequest = new ContentCachingRequestWrapper(httpServletRequest);
chain.doFilter(cachedRequest, response);
}
}
ExceptionHandler
中注入ContentCachingRequestWrapper
@ExceptionHandler({ HttpMessageNotReadableException.class })
public String addStudent(HttpMessageNotReadableException e, ContentCachingRequestWrapper cachedRequest) {
log.error(e.getMessage());
try {
String requestBody = IOUtils.toString(cachedRequest.getContentAsByteArray(), cachedRequest.getCharacterEncoding());
log.error(requestBody);
} catch (IOException ex) {
ex.printStackTrace();
}
return "greeting from @ExceptionHandler";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.