Ver Fonte

:sparkles: 添加切面日志

Twelve615 há 1 ano atrás
pai
commit
f332d8b5b4

+ 92 - 2
crmeb-admin/src/main/java/com/zbkj/admin/aspect/ControllerAspect.java

@@ -1,13 +1,33 @@
 package com.zbkj.admin.aspect;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.qcloud.cos.utils.Jackson;
+import com.zbkj.common.model.user.User;
+import com.zbkj.service.service.UserService;
+import lombok.extern.slf4j.Slf4j;
 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.Aware;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.InputStreamSource;
 import org.springframework.stereotype.Component;
-
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.context.request.RequestAttributes;
+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 org.springframework.web.servlet.View;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
 import java.util.Arrays;
 
 
@@ -17,9 +37,13 @@ import java.util.Arrays;
  */
 @Aspect
 @Component
+@Slf4j
 public class ControllerAspect {
 
-    Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
+    //Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
+
+    @Autowired
+    private UserService userService;
 
     @Pointcut("execution(* com.zbkj.admin.controller.*.*(..))")
     private void pointCutMethodController() {
@@ -29,6 +53,71 @@ public class ControllerAspect {
     @Around("pointCutMethodController()")
     public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
 
+        long startTime = System.currentTimeMillis();
+        try {
+            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
+            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
+            //防止不是http请求的方法,例如:scheduled
+            if (ra == null || sra == null) {
+                log.info("非Http请求 : {}", pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
+                return pjp.proceed();
+            }
+            HttpServletRequest request = sra.getRequest();
+            User user = userService.getInfo();
+            //String authorization = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
+            //log.info("X-Access-Token : {}", authorization);
+            if (user != null) {
+                log.info("USER_NAME : {}", Strings.isNullOrEmpty(user.getRealName())? user.getNickname():user.getRealName());
+            } else {
+                log.info("USER_NAME : 用户未登录,请求头中未携带Authorization");
+            }
+            log.info("URL : " + request.getRequestURL().toString());
+            log.info("HTTP_METHOD : " + request.getMethod());
+            log.info("IP : " + request.getRemoteAddr());
+            log.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
+
+            ObjectMapper objectMapper = Jackson.getObjectMapper();
+            Object[] args = pjp.getArgs();
+            if (args != null) {
+                Object[] objects = new Object[args.length];
+                for (int i = 0; i < objects.length; i++) {
+                    if (args[i] instanceof Aware ||args[i] instanceof View || args[i] instanceof ModelAndView ||args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof InputStreamSource || args[i] instanceof BindingResult || args[i] instanceof MultipartFile) {
+                        // 不打印request
+                        objects[i] = args[i].getClass().getName();
+                        continue;
+                    }
+                    objects[i] = args[i];
+                }
+                log.info("请求参数 : " + objectMapper.writeValueAsString(objects));
+            }
+            startTime = System.currentTimeMillis();
+            Object response = pjp.proceed();
+            // 3.出参打印
+            if (!(response instanceof Aware ||response instanceof View ||response instanceof ModelAndView ||response instanceof ServletRequest || response instanceof ServletResponse || response instanceof InputStreamSource || response instanceof BindingResult|| response instanceof MultipartFile)) {
+                log.info("返回参数 : {}", response != null ? objectMapper.writeValueAsString(response) : "null");
+            } else {
+                log.info("返回参数 : {}", "无法格式化数据");
+            }
+            return response;
+        } catch (Throwable e) {
+            if (e instanceof MethodArgumentNotValidException) {
+                log.info("响应错误:{}", e.getMessage());
+            } else {
+                log.error("响应错误:{}", Arrays.toString(e.getStackTrace()));
+            }
+            e.printStackTrace();
+            //throw e;
+            return pjp.proceed();
+        } finally {
+            long endTime = System.currentTimeMillis();
+            log.info("耗时 : {}ms", (endTime - startTime));
+        }
+    }
+/*
+
+    @Around("pointCutMethodController()")
+    public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
+
         long begin = System.nanoTime();
 
         Object obj = pjp.proceed();
@@ -41,5 +130,6 @@ public class ControllerAspect {
 
         return obj;
     }
+*/
 
 }

+ 92 - 2
crmeb-front/src/main/java/com/zbkj/front/aspect/ControllerAspect.java

@@ -1,13 +1,33 @@
 package com.zbkj.front.aspect;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+import com.qcloud.cos.utils.Jackson;
+import com.zbkj.common.model.user.User;
+import com.zbkj.service.service.UserService;
+import lombok.extern.slf4j.Slf4j;
 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.Aware;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.InputStreamSource;
 import org.springframework.stereotype.Component;
-
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.context.request.RequestAttributes;
+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 org.springframework.web.servlet.View;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
 import java.util.Arrays;
 
 
@@ -17,9 +37,13 @@ import java.util.Arrays;
  */
 @Aspect
 @Component
+@Slf4j
 public class ControllerAspect {
 
-    Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
+    //Logger logger = LoggerFactory.getLogger(ControllerAspect.class);
+
+    @Autowired
+    private UserService userService;
 
     @Pointcut("execution(* com.zbkj.front.controller.*.*(..))")
     private void pointCutMethodController() {
@@ -29,6 +53,71 @@ public class ControllerAspect {
     @Around("pointCutMethodController()")
     public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
 
+        long startTime = System.currentTimeMillis();
+        try {
+            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
+            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
+            //防止不是http请求的方法,例如:scheduled
+            if (ra == null || sra == null) {
+                log.info("非Http请求 : {}", pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
+                return pjp.proceed();
+            }
+            HttpServletRequest request = sra.getRequest();
+            User user = userService.getInfo();
+            //String authorization = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
+            //log.info("X-Access-Token : {}", authorization);
+            if (user != null) {
+                log.info("USER_NAME : {}", Strings.isNullOrEmpty(user.getRealName())? user.getNickname():user.getRealName());
+            } else {
+                log.info("USER_NAME : 用户未登录,请求头中未携带Authorization");
+            }
+            log.info("URL : " + request.getRequestURL().toString());
+            log.info("HTTP_METHOD : " + request.getMethod());
+            log.info("IP : " + request.getRemoteAddr());
+            log.info("CLASS_METHOD : " + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
+
+            ObjectMapper objectMapper = Jackson.getObjectMapper();
+            Object[] args = pjp.getArgs();
+            if (args != null) {
+                Object[] objects = new Object[args.length];
+                for (int i = 0; i < objects.length; i++) {
+                    if (args[i] instanceof Aware ||args[i] instanceof View || args[i] instanceof ModelAndView ||args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof InputStreamSource || args[i] instanceof BindingResult || args[i] instanceof MultipartFile) {
+                        // 不打印request
+                        objects[i] = args[i].getClass().getName();
+                        continue;
+                    }
+                    objects[i] = args[i];
+                }
+                log.info("请求参数 : " + objectMapper.writeValueAsString(objects));
+            }
+            startTime = System.currentTimeMillis();
+            Object response = pjp.proceed();
+            // 3.出参打印
+            if (!(response instanceof Aware ||response instanceof View ||response instanceof ModelAndView ||response instanceof ServletRequest || response instanceof ServletResponse || response instanceof InputStreamSource || response instanceof BindingResult|| response instanceof MultipartFile)) {
+                log.info("返回参数 : {}", response != null ? objectMapper.writeValueAsString(response) : "null");
+            } else {
+                log.info("返回参数 : {}", "无法格式化数据");
+            }
+            return response;
+        } catch (Throwable e) {
+            if (e instanceof MethodArgumentNotValidException) {
+                log.info("响应错误:{}", e.getMessage());
+            } else {
+                log.error("响应错误:{}", Arrays.toString(e.getStackTrace()));
+            }
+            e.printStackTrace();
+            //throw e;
+            return pjp.proceed();
+        } finally {
+            long endTime = System.currentTimeMillis();
+            log.info("耗时 : {}ms", (endTime - startTime));
+        }
+    }
+/*
+
+    @Around("pointCutMethodController()")
+    public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
+
         long begin = System.nanoTime();
 
         Object obj = pjp.proceed();
@@ -41,5 +130,6 @@ public class ControllerAspect {
 
         return obj;
     }
+*/
 
 }