Spring日志切面
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LogAspect {
@Pointcut("execution(* com.xxx..control.*.*(..))")
public void logAll() {
}
@Around("logAll()")
public Object accessLog(ProceedingJoinPoint joinPoint) {
visitLog(joinPoint);// 首先记录接口访问开始
return callAndLogDuration(joinPoint);// 执行切点、记录访问耗时
}
private Object callAndLogDuration(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
try {
long start = System.currentTimeMillis();// 访问开始
Object obj = joinPoint.proceed();// 执行切点任务
long end = System.currentTimeMillis();// 访问结束
Log("接口访问[" + signature.getDeclaringTypeName() + "." + signature.getName() + "]结束,执行耗时["
+ (end - start) + "]毫秒");
return obj;
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
}
}
private void visitLog(ProceedingJoinPoint joinPoint) {
StringBuilder lo = new StringBuilder();
try {
Signature signature = joinPoint.getSignature();
signature.getDeclaringType();
lo.append("访问[" + signature.getDeclaringTypeName() + "." + signature.getName() + "],");
lo.append(getParam(joinPoint));
Log(lo.toString());
} catch (Exception e) {
}
}
private String getParam(ProceedingJoinPoint joinPoint) {
StringBuilder param = new StringBuilder();
param.append("参数[");
for (Object arg : joinPoint.getArgs()) {
param.append(arg + ",");
}
if (joinPoint.getArgs().length > 0) {
param.deleteCharAt(param.length() - 1);
}
param.append("]");
return param.toString();
}
}