package cn.sunline.insd.cus.service.config;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
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 cn.sunline.insd.cus.facility.Log;
@Component
@Aspect
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 定义一个切入点.
* 解释下:
*
* ~ 第一个 * 代表任意修饰符及任意返回值.
* ~ 第二个 * 定义在web包或者子包
* ~ 第三个 * 任意方法
* ~ .. 匹配任意数量的参数.
*/
@Pointcut("execution(* cn.sunline..*Controller.*(..))")
public void logPointcut(){}
@org.aspectj.lang.annotation.Around("logPointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
long start = System.currentTimeMillis();
Object[] args = joinPoint.getArgs();
Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.asList(args).stream();
List<Object> logArgs = stream
.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
.collect(Collectors.toList());
logger.info("====接口调用:{},参数:{} ", joinPoint.getSignature(), JSON.toJSONString(logArgs));
try {
Object result = joinPoint.proceed();
Log.info("返回结果:{}", JSON.toJSONString(result));
long end = System.currentTimeMillis();
logger.info("调用方法[" + joinPoint.getSignature() + "] 耗时 : " + (end - start) + " ms!");
return result;
} catch (Throwable e) {
long end = System.currentTimeMillis();
logger.info("调用方法[" + joinPoint.getSignature() + "] 耗时 : " + (end - start) + " ms! 抛出异常 : "+e.getMessage());
throw e;
}
}
}