/**
|
* Copyright (C) 2018-2020
|
* All rights reserved, Designed By www.yixiang.co
|
* 注意:
|
* 本软件为www.yixiang.co开发研制
|
*/
|
package com.sandu.common.log;
|
|
import com.sandu.common.enums.LogTypeEnums;
|
import com.sandu.common.util.RequestHolder;
|
import com.sandu.common.util.ThrowableUtil;
|
import lombok.extern.slf4j.Slf4j;
|
import org.aspectj.lang.JoinPoint;
|
import org.aspectj.lang.ProceedingJoinPoint;
|
import org.aspectj.lang.annotation.AfterThrowing;
|
import org.aspectj.lang.annotation.Around;
|
import org.aspectj.lang.annotation.Aspect;
|
import org.aspectj.lang.annotation.Pointcut;
|
import org.springframework.stereotype.Component;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
/**
|
* @author hupeng
|
* @date 2018-11-24
|
*/
|
@Component
|
@Aspect
|
@Slf4j
|
public class LogAspect {
|
|
private final LogServiceImpl logService;
|
|
ThreadLocal<Long> currentTime = new ThreadLocal<>();
|
|
public LogAspect(LogServiceImpl logService) {
|
this.logService = logService;
|
}
|
|
/**
|
* 配置切入点
|
*/
|
@Pointcut("@annotation(com.sandu.common.log.Log)")
|
public void logPointcut() {
|
// 该方法无方法体,主要为了让同类中其他方法使用此切入点
|
}
|
|
/**
|
* 配置环绕通知,使用在方法logPointcut()上注册的切入点
|
*
|
* @param joinPoint join point for advice
|
*/
|
@Around("logPointcut()")
|
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
|
Object result;
|
currentTime.set(System.currentTimeMillis());
|
result = joinPoint.proceed();
|
AccessLog log = new AccessLog();
|
log.setLogType(LogTypeEnums.NORMAL.getCode());
|
log.setTime(System.currentTimeMillis() - currentTime.get());
|
currentTime.remove();
|
logService.saveOperation(RequestHolder.getHttpServletRequest(), joinPoint, log);
|
return result;
|
}
|
|
/**
|
* 配置异常通知
|
*
|
* @param joinPoint join point for advice
|
* @param e exception
|
*/
|
@AfterThrowing(pointcut = "logPointcut()", throwing = "e")
|
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
|
AccessLog log = new AccessLog();
|
log.setTime(System.currentTimeMillis() - currentTime.get());
|
currentTime.remove();
|
log.setLogType(LogTypeEnums.ERROR.getCode());
|
log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
|
HttpServletRequest request = RequestHolder.getHttpServletRequest();
|
logService.saveOperation(request, (ProceedingJoinPoint) joinPoint, log);
|
}
|
|
}
|