ControllerLogAspect.java 5.39 KB
/**
 * 
 */
package com.huaheng.framework.aspectj;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;

import lombok.extern.log4j.Log4j2;

/**
 * 记录调用Controller请求日志
 * 
 * @Author AnsonTan
 * @Date 2018-11-12 15:49
 */
@Aspect
@Component
@Log4j2
public class ControllerLogAspect {

    private static final ThreadLocal<Long> timeTreadLocal = new ThreadLocal<>();

    @Pointcut("execution(* com.huaheng..*..controller..*.*(..)) "
        + "&& (@annotation(org.springframework.web.bind.annotation.RequestMapping) "
        + "|| @annotation(org.springframework.web.bind.annotation.GetMapping) "
        + "|| @annotation(org.springframework.web.bind.annotation.PostMapping))")
    public void log() {
        //
    }

    @Before("log()")
    public void before(JoinPoint joinPoint) {
        timeTreadLocal.set(System.currentTimeMillis());
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        // 获取请求的request
        HttpServletRequest request = attributes.getRequest();
        String servletPath = request.getServletPath();

        String keyValue = this.getReqParameter(request);
        log.info("[AOP start ] servletPath = {} {}[{}][{}]", servletPath,
            StringUtils.isEmpty(keyValue) ? "" : "param = " + keyValue, request.getMethod(), this.getIpAddr(request));
    }

    // controller请求结束返回时调用
    @AfterReturning(returning = "result", pointcut = "log()")
    public Object afterReturn(Object result) {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        // 获取请求的request
        HttpServletRequest request = attributes.getRequest();
        String servletPath = request.getServletPath();
        long startTime = timeTreadLocal.get();
        long callTime = System.currentTimeMillis() - startTime;
        log.info("[AOP return] servletPath = {} result = {}[{}ms]", servletPath,
            JSON.toJSONString(result), callTime);
        return result;
    }

    /**
     * 获取所有请求参数,封装为map对象
     *
     * @return
     */
    public Map<String, Object> getParameterMap(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String, Object> parameterMap = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getParameter(key);
            String keyValue = key + " : " + value + " ; ";
            stringBuilder.append(keyValue);
            parameterMap.put(key, value);
        }
        return parameterMap;
    }

    public String getReqParameter(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Enumeration<String> enumeration = request.getParameterNames();
        StringBuffer returnStringBuffer = new StringBuffer();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getParameter(key);
            returnStringBuffer.append(key + "=" + (StringUtils.isEmpty(value) ? "null" : value));
            if (enumeration.hasMoreElements()) {
                returnStringBuffer.append("&");
            }
        }
        return returnStringBuffer.toString();
    }

//    public String getReqParameter(HttpServletRequest request) {
//        if (request == null) {
//            return null;
//        }
//        Enumeration<String> enumeration = request.getParameterNames();
//        JSONArray jsonArray = new JSONArray();
//        while (enumeration.hasMoreElements()) {
//            String key = enumeration.nextElement();
//            String value = request.getParameter(key);
//            JSONObject json = new JSONObject();
//            json.put(key, value);
//            jsonArray.add(json);
//        }
//        return jsonArray.toString();
//    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0];
    }
}