代码:
package com.yh.webapp.aop;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import com.yh.webapp.model.Users;
@Component
@Aspect
public class LogAop {
private Logger log = LogManager.getLogger();
public static final String edp="execution(* com.yh.webapp.service.*.*(..))";
@Around(edp)
public Object timeAround(ProceedingJoinPoint joinPoint){
Object obj = null;
Object [] args=joinPoint.getArgs();
long startTime = System.currentTimeMillis();
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
log.error("统计某方法执行耗时环绕通知出错", e);
}
// 获取执行的方法名
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 打印耗时的信息
Users user=(Users) ServletActionContext.getRequest().getSession().getAttribute("user");
log.info("*****开始记录日志*****");
if(user!=null){
log.info("用户:"+user.getName()+" 执行了:"+joinPoint.getSignature().getName()+"耗时:"+(endTime - startTime));
}
else{
log.info("用户未登陆:执行了:"+joinPoint.getSignature().getName()+"耗时:"+(endTime - startTime));
}
return obj;
}
}