package net.northking.cctp.upperComputer.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志切面：对业务系统的每一个请求做记录
 */
@Aspect
@Component
public class ControllerAspect {

    private static final Logger log = LoggerFactory.getLogger(ControllerAspect.class);

    /**
     * 对请求开始结束做日志
     *
     * @param proceedingJoinPoint
     * @return 请求结果
     */
    @Around("execution(public * net.northking.cctp.upperComputer.controller..*(..))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 请求开始时间
        long startTime = System.currentTimeMillis();
        // 请求映射控制类
        String clazzName = proceedingJoinPoint.getTarget().getClass().getSimpleName();
        // 请求方法
        String methodName = proceedingJoinPoint.getSignature().getName();
        // 请求用户
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userName = (String) request.getAttribute("userName");
        if (userName == null) {
            userName = "";
        }
        log.info("请求开始，请求映射控制类：【{}】，请求方法：【{}】，请求用户：【{}】", clazzName, methodName, userName);
        try {
            Object result = proceedingJoinPoint.proceed();
            log.info("请求结束，请求映射控制类：【{}】，请求方法：【{}】，请求耗时：【{}毫秒】，请求用户：【{}】", clazzName, methodName, System.currentTimeMillis() - startTime, userName);
            return result;
        } catch (Throwable e) {
            log.error("请求异常，请求映射控制类：【{}】，请求方法：【{}】，请求耗时：【{}毫秒】，请求用户：【{}】", clazzName, methodName, System.currentTimeMillis() - startTime, userName);
            throw e;
        }
    }

}
