我想使用 Spring 为 API 实现 Rest 日志记录。我试过这个:
public static String readPayload(final HttpServletRequest request) throws IOException {
String payloadData = null;
ContentCachingRequestWrapper contentCachingRequestWrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (null != contentCachingRequestWrapper) {
byte[] buf = contentCachingRequestWrapper.getContentAsByteArray();
if (buf.length > 0) {
payloadData = new String(buf, 0, buf.length, contentCachingRequestWrapper.getCharacterEncoding());
}
}
return payloadData;
}
public static String getResponseData(final HttpServletResponse response) throws IOException {
String payload = null;
ContentCachingResponseWrapper wrapper =
WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
wrapper.copyBodyToResponse();
}
}
return payload;
}
@PostMapping(value = "/v1", consumes = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE })
public PaymentResponse handleMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest requestCacheWrapperObject = new ContentCachingRequestWrapper(request);
requestCacheWrapperObject.getParameterMap();
.raw_request(readPayload(requestCacheWrapperObject))
.raw_response(getResponseData(response))
}
但是我的请求和响应都为 NULL。 您知道从请求和响应中获取有效负载的正确方法是什么吗?
最佳答案
所以你只需要拥有自己的拦截器即可。
@Component
public class HttpRequestResponseLoggingInterceptorAdapter extends HandlerInterceptorAdapter {
@Autowired
private LoggingUtils loggingutils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
loggingutils.preHandle(request, response);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) {
try {
loggingutils.postHandle(request, response);
} catch(Exception e) {
System.out.println("Exception while logging outgoing response");
}
}
}
完成后,您需要将新拦截器绑定(bind)到现有拦截器。
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private HttpRequestResponseLoggingInterceptorAdapter httpRequestResponseLoggingInterceptorAdapter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(httpRequestResponseLoggingInterceptorAdapter);
}
}
完成后,您对 handlemessage 方法的传入请求将被拦截,并且可以执行您想要的任何前/后处理。 在这种情况下登录。
请告诉我这是否有帮助。
关于java - Spring API 中的日志请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261567/