JAVA統一介面日誌切面列印方法引數

cg_Amaz1ng發表於2020-09-28
package com.gaara.musicscore.config.log;


import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private final String httpStartTime = "HTTP_START_TIME";

    @Pointcut("execution(public * com.gaara.musicscore.api..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        try {
            if (!logger.isDebugEnabled()) {
                return;
            }
            // 接收到請求,記錄請求內容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            request.setAttribute(httpStartTime, System.currentTimeMillis());

            StringBuilder sb = new StringBuilder(1000);
            sb.append("\n-----------------------------開始呼叫:-----------------------------\n");
            sb.append("Controller: ").append(joinPoint.getSignature().getDeclaringType()).append("\n");
            sb.append("Method    : ").append(joinPoint.getSignature().getName()).append("\n");
            sb.append("Header    : {").append("\n");
            Enumeration<String> requestHeader = request.getHeaderNames();
            while (requestHeader.hasMoreElements()) {
                String headerKey = requestHeader.nextElement();
                // 列印所有Header值
                sb.append("    ").append(headerKey).append(" : ").append(request.getHeader(headerKey)).append("\n");
            }
            sb.append("}").append("\n");
            sb.append("Params    : ").append(getParams(joinPoint)).append("\n");
            sb.append("URI       : ").append(request.getMethod()).append(" ").append(request.getRequestURI()).append("\n");
            sb.append("-----------------------------開始呼叫:-----------------------------");
            // 記錄下請求內容
            logger.debug(sb.toString());
        } catch (Exception e) {
            logger.warn("切面處理前錯誤", e);
        }
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
        try {
            if (!logger.isDebugEnabled()) {
                return;
            }
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            long ms = System.currentTimeMillis() - (long) request.getAttribute(httpStartTime);
            // 處理完請求,返回內容
            StringBuilder sb = new StringBuilder(50);
            sb.append("\n-----------------------------結束呼叫:-----------------------------\n");
            sb.append("Controller: ").append(joinPoint.getSignature().getDeclaringType()).append("\n");
            sb.append("URI       : ").append(request.getMethod()).append(" ").append(request.getRequestURI()).append("\n");
            sb.append("Method    : ").append(joinPoint.getSignature().getName()).append("\n");
            sb.append("return    : ").append(JSON.toJSONString(ret)).append("\n");
            sb.append("CostTime  : ").append(ms).append("ms\n");
            sb.append("-----------------------------結束呼叫:-----------------------------");
            logger.debug(sb.toString());
        } catch (Exception e) {
            logger.warn("切面處理後錯誤", e);
        }

    }

    private StringBuilder getParams(JoinPoint joinPoint) {
        StringBuilder params = new StringBuilder();
        for (Object arg : joinPoint.getArgs()) {
            try {
                if (!(arg instanceof ServletRequest)
                        && !(arg instanceof ServletResponse)
                        && !(arg instanceof MultipartFile)
                        && !(arg instanceof ModelAndView)
                        && !(arg instanceof Model)
                ) {
                    params.append(", ");
                    params.append(JSON.toJSONString(arg));
                }
            } catch (Exception e) {
                logger.warn("未知型別轉換錯誤:" + arg.getClass().getSimpleName());
            }
        }
        return params;
    }

}

 

相關文章