@ResponseBody
@RequestMapping(value = "order/pickupinfo", method = RequestMethod.POST, produces = {
"application/json;charset=UTF-8" })
public ResReslt orderList(String req, HttpServletResponse response) {
saveLog(。。。)//保存日志方法
return tt;
}
如果使用上面的方面编写编写输出日志的话,每个方法中都需要写saveLog(。。。),这样搞维护起来比较麻烦,也有可能会有遗漏的地方没有输出日志。
下面我们通过实现import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
这个接口的方式输出日志:
package com.cloud.tools.aop;
import org.slf4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.cloud.api.pojo.ResPageReslt;
import com.cloud.api.pojo.ResReslt;
import com.cloud.api.util.ObjToJson;
import com.cloud.log.ReqAndResLog;
@ControllerAdvice
public class ResponseBodyAdviceImp implements ResponseBodyAdvice{
Logger jsonLog = org.slf4j.LoggerFactory.getLogger(ResponseBodyAdviceImp.class);
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(null !=body){
String flag = body.toString();
ReqAndResLog reqAndResLog = new ReqAndResLog();
ReqAndResLog temp = reqAndResLog.getInfo();
if(temp !=null){
//已经存在日志对象时,进行比较
if(flag.toString().equals(temp.getRes())){
//移除日志对象
reqAndResLog.remove();
StringBuffer res = new StringBuffer(60);
res.append(returnType.getMethod().getName()).append(";");
if(body instanceof ResReslt){
res.append(ObjToJson.ResResltToStr((ResReslt)body));
}else if(body instanceof ResPageReslt){
res.append(ObjToJson.ResPageResltToStr((ResPageReslt)body));
}
jsonLog.debug(res.toString());
}
}else{
//不存在日志对象,加入
reqAndResLog.setRes(flag);
reqAndResLog.setInfo(reqAndResLog);
}
}
return body;
}
}
package com.cloud.log;
public class ReqAndResLog {
public static final ThreadLocal
//请求参数
private String req;
private String res;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public String getReq() {
return req;
}
public void setReq(String req) {
this.req = req;
}
public void setInfo(ReqAndResLog reqAndResLog){
REQ_AND_RES_LOG.set(reqAndResLog);
}
public ReqAndResLog getInfo(){
return REQ_AND_RES_LOG.get();
}
public void remove(){
REQ_AND_RES_LOG.remove();
}
}
ReqAndResLog:作用是防止同样的日志输出两边;
2.配置文件