


package com.jwipc.log.endpoint;

import com.jwipc.log.dto.LogDTO;
import com.jwipc.log.logic.LogAnalysisLogic;
import com.jwipc.util.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.HttpHeaders;
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.lang.reflect.Method;

/**
 * <p>方法报错，日志记录增强</p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
@Slf4j
@Component
@ConditionalOnBean(name = "logAnalysisLogic")
@RequiredArgsConstructor
public class LogbookThrowsAdvice implements ThrowsAdvice {
    private final LogAnalysisLogic logAnalysisLogic;



    public void afterThrowing(Method method, Object[] pointArgs, Object target, Throwable subclass) throws Throwable {
        // 取得请求参数
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        final Class<?> targetClass = target.getClass();
        String url = request.getRequestURI();
        final String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        String ipAddress = RequestUtil.getIpAddress(request);
        final LogDTO logDTO = LogDTO.buildByRequest(ipAddress, userAgent);
        logAnalysisLogic.analysisThrowException(targetClass, method, pointArgs, subclass, url, logDTO);
    }
}
