@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-10-04 14:48:21 发布
本文档介绍了如何在Spring MVC控制器中实现全局的日志处理,记录了请求地址、方式、参数和操作者,使用ResponseBodyAdvice和RequestBodyAdvice进行前后端交互的参数管理和日志输出。
摘要由CSDN通过智能技术生成