packagecom.yule.common.interceptor;importcom.ch.common.util.CommonTool;importcom.yule.manage.interfacelog.entity.InterfaceLog;importcom.yule.manage.interfacelog.entity.InterfaceLogHolder;importcom.yule.manage.interfacelog.service.InterfaceLogService;importorg.apache.commons.lang3.StringUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.Map;/*** 日志拦截器:记录调用日志
*@authoryule*/
public class InterfaceLogInterceptor extendsHandlerInterceptorAdapter {
@AutowiredprivateInterfaceLogService interfaceLogService;private final Logger logger = LoggerFactory.getLogger(InterfaceLogInterceptor.class);
@Overridepublic booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throwsException {try{
InterfaceLog interfaceLog= newInterfaceLog();
interfaceLog.setStatus(InterfaceLog.STATUS_SUCCESS);//方法返回发出请求的客户机的IP地址
interfaceLog.setCallerIp(request.getRemoteAddr());
interfaceLog.setInterfaceName(request.getRequestURI());// interfaceLog.setLocalIp(request.getLocalAddr());//方法返回WEB服务器的IP地址。//返回一个包含请求消息中的所有参数名的Enumeration对象。通过遍历这个Enumeration对象,就可以获取请求消息中所有的参数名。
Map paramsMap =request.getParameterMap();if(CommonTool.isNotNullOrBlock(paramsMap)){
StringBuilder stringBuilder= newStringBuilder();for(Map.Entryentry : paramsMap.entrySet()){
stringBuilder.append(entry.getKey()).append(": ").append(StringUtils.join(entry.getValue())).append("; ");
}
interfaceLog.setCallerParams(stringBuilder.toString());
}this.interfaceLogService.insert(interfaceLog);//线程变量存值
InterfaceLogHolder.setIdStringThreadLocalValue(interfaceLog.getId());
}catch(Exception e) {
logger.error("接口调用记录错误信息出错;调用者ip:" + request.getRemoteHost() + ", 调用者ip:" + request.getRemoteAddr() + ", 接口名:" +request.getRequestURI(), e);
}return true;
}
}