package cn.palmte.work.config.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author xiongshiyan
 * 统一打印日志
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private LogExcluder logExcluder;

    @Pointcut("execution(public * cn.palmte.work.controller..*.*(..))")
    public void webLog(){}

    @Around(value = "webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        if(logExcluder.needExcluded(request.getRequestURI())){
            return proceedingJoinPoint.proceed();
        }

        logger.info("REQUEST : " + request.getRequestURI() + " : "
                +(proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName() + " : ")
                + Arrays.toString(proceedingJoinPoint.getArgs()));

        Object proceed = proceedingJoinPoint.proceed();

        logger.info("RESPONSE : " + proceed);
        return proceed;
    }
}
