主要拦截前端或后天的请求,打印请求方法参数、返回值、耗时、异常的日志。方便开发调试,能很快定位到问题出现在哪个方法中。
前端请求拦截,mvc的拦截器
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import com.xxx.eduyun.sdk.log.ApplicationLogging;
import com.xxx.flipclass.sdk.client.utils.TimeUtil; /**
* <b>function:</b> spring mvc 请求拦截器
* @author hoojo
* @createDate 2016-11-24 下午3:19:27
* @file MVCRequestInterceptor.java
* @package com.xxx.eduyun.app.mvc.interceptor
* @project eduyun-app-web
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class MVCRequestInterceptor extends ApplicationLogging implements HandlerInterceptor { private static final ObjectMapper mapper = new ObjectMapper();
private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-startTimed"); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { info("##############################【一个MVC完整请求开始】##############################"); info("*******************MVC业务处理开始**********************");
try {
long timed = System.currentTimeMillis();
startTimeThreadLocal.set(timed); String requestURL = request.getRequestURI();
info("当前请求的URL:【{}】", requestURL);
info("执行目标方法: {}", handler); Map<String, ?> params = request.getParameterMap();
if (!params.isEmpty()) {
info("当前请求参数打印:");
print(request.getParameterMap(), "参数");
}
} catch (Exception e) {
error("MVC业务处理-拦截器异常:", e);
}
info("*******************MVC业务处理结束**********************"); return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { info("*******************一个MVC 视图渲染开始**********************"); try {
info("执行业务逻辑代码耗时:【{}】", TimeUtil.formatTime(new Date().getTime() - startTimeThreadLocal.get()));
String requestURL = request.getRequestURI();
info("当前请求的URL:【{}】", requestURL); if (modelAndView != null) {
info("即将返回到MVC视图:{}", modelAndView.getViewName()); if (modelAndView.getView() != null) {
info("返回到MVC视图内容类型ContentType:{}", modelAndView.getView().getContentType());
} if (!modelAndView.getModel().isEmpty()) { info("返回到MVC视图{}数据打印如下:", modelAndView.getViewName());
print(modelAndView.getModel(), "返回数据");
}
}
} catch (Exception e) {
error("MVC 视图渲染-拦截器异常:", e);
} info("*******************一个MVC 视图渲染结束**********************");
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { try {
String requestURL = request.getRequestURI();
info("MVC返回请求完成URL:【{}】", requestURL);
info("MVC返回请求完成耗时:【{}】", TimeUtil.formatTime(new Date().getTime() - startTimeThreadLocal.get()));
if (ex != null) {
info("MVC返回请求发生异常:", ex.getMessage());
error("异常信息如下:", ex);
}
} catch (Exception e) {
error("MVC完成返回-拦截器异常:", e);
} info("##############################【一个MVC完整请求完成】##############################");
} private void print(Map<String, ?> map, String prefix) {
if (map != null) {
Set<String> keys = map.keySet();
Iterator<String> iter = keys.iterator();
while (iter.hasNext()) { String name = iter.next();
if (name.contains("org.springframework.validation.BindingResult")) {
continue;
} String value = "";
try {
value = mapper.writeValueAsString(map.get(name));
} catch (Exception e) {
error("转换参数【{}】发生异常:", name, e);
}
info("{} \"{}\": {}", prefix, name, value);
}
}
}
}
spring-mvc.xml增加配置内容
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/exceltemplate/**" />
<mvc:exclude-mapping path="/statics/**" />
<mvc:exclude-mapping path="/global/**" />
<mvc:exclude-mapping path="/denied/**" />
<mvc:exclude-mapping path="/favicon.ico" />
<mvc:exclude-mapping path="/index.jsp" />
<bean class="com.xxx.eduyun.app.mvc.interceptor.MVCRequestInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
过滤静态资源,一些静态资源不需要拦截,在这里配置黑名单不让它进入拦截器。
下面是sdk接口拦截器,用到spirng的aop的MethodIntercept
package com.xxx.flipclass.sdk.framework.aop; import java.lang.reflect.Method;
import java.util.Date; import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper; import com.xxx.flipclass.sdk.client.utils.ParameterNameUtils;
import com.xxx.flipclass.sdk.client.utils.TimeUtil; /**
* <b>function:</b> Spring 接口调用拦截器,主要拦截com.xxx.*.sdk.client对外接口
* @author hoojo
* @createDate 2016-11-24 下午5:39:57
* @file ExecutionApiLogMethodInterceptor.java
* @package com.xxx.eduyun.sdk.framework
* @project eduyun-sdk-service
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class ExecutionApiLogMethodInterceptor implements MethodInterceptor { private Logger log = LogManager.getLogger(ExecutionApiLogMethodInterceptor.class);
private static final ObjectMapper mapper = new ObjectMapper(); @Override
public Object invoke(MethodInvocation invocation) throws Throwable { info("************************************【接口调用拦截开始】*************************************");
String targetName = invocation.getThis().getClass().getSimpleName();
Method method = invocation.getMethod();
String methodName = method.getName(); info("系统开始执行方法:{}.{}", targetName, methodName); info("【{}.{}】方法参数打印如下:", targetName, methodName);
Object[] args = invocation.getArguments(); //printArgs(args, method, invocation.getThis().getClass());
printArgs(args, method); try {
long timed = System.currentTimeMillis(); Object result = invocation.proceed(); info("【{}.{}】方法执行完成,耗时:【{}】", targetName, methodName, TimeUtil.formatTime(new Date().getTime() - timed));
info("【{}.{}】方法执行返回结果:{}", targetName, methodName, result); info("【{}.{}】方法返回数据打印如下:", targetName, methodName);
printResult(result);
info("************************************【接口调用拦截结束*】************************************"); return result;
} catch (Throwable throwable) {
error("外部接口调用方法【{}.{}】异常:", targetName, methodName, throwable); info("************************************【接口异常拦截结束】*************************************");
throw throwable;
}
} private void printArgs(Object[] args, Method method) {
try { String[] argNames = null;
try {
argNames = ParameterNameUtils.getMethodParamNames(method);
} catch (Exception e) {
error("获取参数名称异常:", e);
} if (args != null) {
for (int i = 0; i < args.length; i++) {
String argName = "";
if (argNames != null && argNames.length >= i) {
argName = argNames[i];
} if (args[i] != null) {
String value = "";
try {
value = mapper.writeValueAsString(args[i]);
} catch (Exception e) {
error("转换参数 \"{}\" 发生异常:", argName, e);
}
info("【参数 \"{}\" 】:({})", argName, value);
} else {
info("参数 \"{}\":NULL", argName);
}
}
}
} catch (Exception e) {
error("【接口调用拦截器】打印方法执行参数异常:", e);
}
} private void printResult(Object result) {
if (result != null) {
try {
info("【返回数据】:({})", mapper.writeValueAsString(result));
} catch (Exception e) {
error("返回数据打印异常:", e);
}
} else {
info("【返回数据】:NULL");
}
} protected final void error(String msg, Object... objects) {
log.error(msg, objects);
} protected final void info(String msg, Object... objects) {
log.info(msg, objects);
}
}
上面使用到了方法参数获取的工具类,代码如下:
package com.xxx.flipclass.sdk.client.utils; import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays; import org.springframework.asm.ClassReader;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.ClassWriter;
import org.springframework.asm.Label;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.Opcodes;
import org.springframework.asm.Type; /**
* <b>function:</b> 获取方法参加名称
* @createDate 2016-11-25 下午3:40:33
* @file ParameterNameUtils.java
* @package com.xxx.flipclass.sdk.client.utils
* @project flipclass-sdk-client
* @version 1.0
*/
public abstract class ParameterNameUtils { /**
* 获取指定类指定方法的参数名
*
* @param clazz 要获取参数名的方法所属的类
* @param method 要获取参数名的方法
* @return 按参数顺序排列的参数名列表,如果没有参数,则返回null
*/
public static String[] getMethodParamNames(Class<?> clazz, final Method method) throws Exception { try { final String[] paramNames = new String[method.getParameterTypes().length];
String className = clazz.getName(); int lastDotIndex = className.lastIndexOf(".");
className = className.substring(lastDotIndex + 1) + ".class";
InputStream is = clazz.getResourceAsStream(className); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassReader cr = new ClassReader(is); cr.accept(new ClassVisitor(Opcodes.ASM4, cw) {
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
final Type[] args = Type.getArgumentTypes(desc);
// 方法名相同并且参数个数相同
if (!name.equals(method.getName()) || !sameType(args, method.getParameterTypes())) {
return super.visitMethod(access, name, desc, signature, exceptions);
}
MethodVisitor v = cv.visitMethod(access, name, desc, signature, exceptions);
return new MethodVisitor(Opcodes.ASM4, v) {
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
int i = index - 1;
// 如果是静态方法,则第一就是参数
// 如果不是静态方法,则第一个是"this",然后才是方法的参数
if (Modifier.isStatic(method.getModifiers())) {
i = index;
}
if (i >= 0 && i < paramNames.length) {
paramNames[i] = name;
}
super.visitLocalVariable(name, desc, signature, start, end, index);
} };
}
}, 0);
return paramNames;
} catch (Exception e) {
throw e;
}
} /**
* 比较参数类型是否一致
* @param types asm的类型({@link Type})
* @param clazzes java 类型({@link Class})
* @return
*/
private static boolean sameType(Type[] types, Class<?>[] clazzes) {
// 个数不同
if (types.length != clazzes.length) {
return false;
} for (int i = 0; i < types.length; i++) {
if (!Type.getType(clazzes[i]).equals(types[i])) {
return false;
}
}
return true;
} /**
* 获取方法的参数名
* @param Method
* @return argsNames[]
*/
public static String[] getMethodParamNames(final Method method) throws Exception { return getMethodParamNames(method.getDeclaringClass(), method);
} public static void main(String[] args) throws Exception {
Class<ParameterNameUtils> clazz = ParameterNameUtils.class; Method method = clazz.getDeclaredMethod("getMethodParamNames", Method.class);
String[] parameterNames = ParameterNameUtils.getMethodParamNames(method);
System.out.println(Arrays.toString(parameterNames)); method = clazz.getDeclaredMethod("sameType", Type[].class, Class[].class);
parameterNames = ParameterNameUtils.getMethodParamNames(method);
System.out.println(Arrays.toString(parameterNames));
}
}
最后需要添加配置,拦截哪些接口或是实现类,具体看个人业务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <bean id="externalApiMethodInterceptor" class="com.xxx.flipclass.sdk.framework.aop.ExecutionApiLogMethodInterceptor" /> <aop:config proxy-target-class="true">
<aop:pointcut id="externalApiMethodPointcut" expression="!execution(* com.xxx.flipclass.sdk.client.interfaces..*.loginInfoService.*(..)) and (execution(* com.xxx.*.sdk.client.interfaces..*.*Client*.*(..)) || execution(* com.xxx.*.sdk.client.interfaces..*.*Service*.*(..)))" />
<aop:advisor advice-ref="externalApiMethodInterceptor" pointcut-ref="externalApiMethodPointcut" />
</aop:config>
</beans>