@Slf4j
@ControllerAdvice
public class GlobalInterfaceLogHandler implements ResponseBodyAdvice<Object>, RequestBodyAdvice {
private String bodyParams = "无";
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
StringBuffer sb = new StringBuffer();
sb.append("\n请求访问地址:{}");
sb.append("\n请求方式:{}");
sb.append("\n请求body参数:{}");
sb.append("\n操作人:{}");
sb.append("\n返回结果:{}");
String username = "获取服务当前用户信息";
log.info(sb.toString(),
request.getURI(),
request.getMethodValue(),
getBodyParams(),
username,
JacksonUtil.obj2Str(body));
return body;
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
return inputMessage;
}
@SneakyThrows
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
setBodyParams(body);
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
private void setBodyParams(Object body) throws IOException {
this.bodyParams = "body转json字符串";
}
private String getBodyParams() {
String bodyParams = "无";
if(!bodyParams.equals(this.bodyParams)){
bodyParams = this.bodyParams;
this.bodyParams = "无";
}
return bodyParams;
}
Spring Boot 接口全局日志打印
最新推荐文章于 2024-05-14 10:43:44 发布