前言
在日常工作中,我們免不了要打印很多l(xiāng)og。而大部分需要輸出的log又是重復(fù)的(例如傳入?yún)?shù),返回值)。
因此,通過AOP方式來進(jìn)行日志管理可以減少很多代碼量,也更加優(yōu)雅。
主要使用技術(shù):Aspect,Javassist
(本文旨在提供實(shí)現(xiàn)示例,因此不做過多的原理說明。)
本文由作者三汪首發(fā)于簡書。
代碼示例
在Sringboot環(huán)境下,將本文提供的代碼及依賴復(fù)制到你的項(xiàng)目中,可直接使用。
Maven依賴
(不包含slf4j部分依賴)
<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
代碼部分
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
@Aspect
@Component
public class MethodLogAop {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodLogAop.class);
/**
* 切點(diǎn)
* 配置需要添加切面通知的包路徑
*/
@Pointcut("(execution(* com.wolfgy.demo.service..*.*(..)))")//||(execution(* com.wolfgy.demo.web..*.*(..)))
public void webLog(){}
/**
* 前置通知
* @param joinPoint 切點(diǎn)
* @throws Throwable 異常
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
LOGGER.info("類名:" + clazzName);
String methodName = joinPoint.getSignature().getName();
LOGGER.info("方法名:" + methodName);
String[] paramNames = getFieldsName(this.getClass(), clazzName, methodName);
Object[] args = joinPoint.getArgs();
for(int k=0; k<args.length; k++){
LOGGER.info("參數(shù)名:" + paramNames[k] + ",參數(shù)值:" + JSON.toJSONString(args[k]));
}
}
/**
* 得到方法參數(shù)的名稱
* @param cls 類
* @param clazzName 類名
* @param methodName 方法名
* @return 參數(shù)名數(shù)組
* @throws NotFoundException 異常
*/
private static String[] getFieldsName(Class<?> cls, String clazzName, String methodName) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++){
paramNames[i] = attr.variableName(i + pos); //paramNames即參數(shù)名
}
return paramNames;
}
/**
* 后置通知
* 打印返回值日志
* @param ret 返回值
* @throws Throwable 異常
*/
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
LOGGER.info("類名:" + clazzName);
String methodName = joinPoint.getSignature().getName();
LOGGER.info("方法名:" + methodName);
LOGGER.info("返回值 : " + JSON.toJSONString(ret));
}
}
代碼效果
2017-11-23 13:17:28.865 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 類名:com.wolfgy.demo.service.DemoService
2017-11-23 13:17:28.867 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 方法名:save
2017-11-23 13:17:29.025 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 參數(shù)名:project,參數(shù)值:{"name":"demo"}
2017-11-23 13:17:29.273 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 類名:com.wolfgy.demo.service.DemoService
2017-11-23 13:17:29.273 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 方法名:save
2017-11-23 13:17:29.273 INFO 5056 --- [nio-8081-exec-1] com.wolfgy.demo.aspectj.MethodLogAop : 返回值 : null
補(bǔ)充說明
execution語法:
語法表達(dá)式:
execution(<修飾符> <返回類型> <類路徑> <方法名>(<參數(shù)列表>) <異常模式> )
其中,修飾符和異常是可選的,如果不加類路徑,則默認(rèn)對所有的類生效。
常用實(shí)例:
1.通過方法簽名、返回值定義切點(diǎn):
execution(public * *Service(..)):定位于所有類下返回值任意、方法入?yún)㈩愋?、?shù)量任意,public類型的方法
execution(public String *Service(..)):定位于所有類下返回值為String、方法入?yún)㈩愋?、?shù)量任意,public類型的方法
2.通過類包定義切點(diǎn):
execution(* com.yc.controller.BaseController+.*(..)):匹配任意返回類型,對應(yīng)包下BaseController類及其子類等任意方法。
execution(* com.*.(..)):匹配任意返回類型,com包下所有類的所有方法
execution(* com..*.(..)):匹配任意返回類型,com包、子包下所有類的所有方法
(注意:.表示該包下所有類,..則涵括其子包。)
3.通過方法入?yún)⒍x切點(diǎn)
(這里*表示任意類型的一個參數(shù),..表示任意類型任意數(shù)量的參數(shù))
execution(* speak(Integer,*)):匹配任意返回類型,所有類中只有兩個入?yún)?,第一個入?yún)镮nteger,第二個入?yún)⑷我獾姆椒?br>
execution(* speak(..,Integer,..)):匹配任意返回類型,所有類中至少有一個Integer入?yún)?,但位置任意的方法?/p>
以上。
希望我的文章對你能有所幫助。
我不能保證文中所有說法的百分百正確,
但我能保證它們都是我的理解和感悟以及拒絕直接復(fù)制黏貼(確實(shí)需要引用的部分我會附上源地址)。
有什么意見、見解或疑惑,歡迎留言討論。