package com.sunshijia.angry.manager.aop;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.sunshijia.angry.manager.common.Message;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
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 org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @ClassName: ControllerLogAspect
* @Description: 记录调用的控制层log切面
* 无异常:@Around(proceed()之前的部分) → @Before → 方法执行 → @Around(proceed()之后的部分) → @After → @AfterReturning
* 有异常:@Around(proceed(之前的部分)) → @Before → 扔异常ing → @After → @AfterThrowing
* @author
* @date 2019年5月8日 上午9:26:44
* @version 1.0
*/
@Aspect
@Component
public class ControllerLogAspect {
Logger log = LoggerFactory.getLogger(ControllerLogAspect.class);
// 切入点描述 这个是service包的切入点
@Pointcut("execution(public * com.sunshijia.angry.controller.LoginController.login(..))")
public void ctrlLog() {
}
/**
* @Description: 方法正常结束
* @param joinPoint 切入点
* @param msg 结束返回值(统一类型)
* @author
* @date 2019年5月8日 上午9:49:01
*/
@AfterReturning(pointcut = "ctrlLog()", returning = "msg")
public void logTheEnd(JoinPoint joinPoint, Message<Object> msg) {
// 获取当前登录用户
String userName = this.getUserName();
// 获取请求方法名
String methodName = joinPoint.getSignature().getName();
// 获取请求参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
//logger.info("当前登录用户:" + userName + ",请求为方法:" + methodName + ",参数为:" + args + ",状态码:" + msg.getCode() + ",提示信息:" + msg.getMsg());
log.info("当前登录用户:{},请求为方法:{},参数为:{},状态码:{},提示信息:{}",userName,methodName,args,msg.getCode(),msg.getMsg());
}
/**
* @Description: 方法异常结束
* @param joinPoint 切入点
* @param ex 异常信息
* @author
* @date 2019年5月8日 上午9:49:32
*/
@AfterThrowing(pointcut = "ctrlLog()", throwing = "ex")
public void logError(JoinPoint joinPoint, Exception ex) {
// 获取当前登录用户
String userName = this.getUserName();
// 获取请求方法名
String methodName = joinPoint.getSignature().getName();
// 获取请求参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
//logger.error("当前登录用户:" + userName + ",请求为方法:" + methodName + ",参数为:" + args + ",异常为:" + ex);
log.error("当前登录用户:{},请求为方法:{},参数为:{},异常为:{}",userName,methodName,args,ex.getMessage());
}
/**
* @Description: 获取当前登录用户
* @return 用户名
* @author
* @date 2019年5月8日 上午9:57:14
*/
private String getUserName() {
// 获取request
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
// 获取token
String token = request.getHeader("token");
// 根据token获取当前登录用户
String userName = token;
return userName;
}
}