소스 검색

增加拦截器日志

baihe 3 년 전
부모
커밋
361120bf50

+ 102 - 0
common-base/src/main/java/com/factory/base/aspect/LogAspect.java

@@ -0,0 +1,102 @@
+package com.factory.base.aspect;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+
+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.aspectj.lang.reflect.MethodSignature;
+import org.springframework.stereotype.Component;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.multipart.MultipartFile;
+
+import com.factory.base.util.JacksonJsonUtils;
+
+import cn.hutool.core.lang.UUID;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * 通过切面 记录请求日志
+ *
+ * @author edz
+ */
+@Slf4j
+@Aspect
+@Component
+public class LogAspect {
+
+    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
+	public void logPointAround() {
+	}
+    
+    @Around("logPointAround()")
+    public Object doAroundLog(ProceedingJoinPoint thisJoinPoint) throws Throwable{
+        Object r = null;
+        String method = thisJoinPoint.getSignature().getName();
+        LocalDateTime startTime = LocalDateTime.now();
+        String uuid = UUID.fastUUID().toString();
+        String url = null;
+        Object userId = null;
+        Map param = null;
+        boolean flag = false;
+        try {
+        	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+            HttpServletRequest request = requestAttributes.getRequest();
+
+            userId = request.getAttribute("UserId");
+            url = request.getRequestURL().toString();      
+         
+            param = getArgs(thisJoinPoint,((MethodSignature)thisJoinPoint.getSignature()).getParameterNames());
+            log.info("\033[1;32m[访问地址:{}] [方法:{}] [{}] [userId:{}] [参数:{}]\033[0m",url,method,uuid,userId,param);
+            r = thisJoinPoint.proceed ();//被代理对象执行结果
+           
+        } catch (Throwable e) {
+        	flag = true;
+            throw e;//异常信息有统一异常处理器处理
+        }
+        log.info("\033[1;32m[访问地址:{}] [方法:{}] [{}] [执行时间:{}(豪秒)] [{}]\033[0m",url,method,uuid,Duration.between(startTime, LocalDateTime.now()).toMillis(),flag?"异常":"正常");
+        return r;
+    }
+    private static String types = "java.lang.Integer,java.lang.Double,java.lang.Float,java.lang.Long,java.lang.Short,java.lang.Byte,java.lang.Boolean,java.lang.Char,java.lang.String,int,double,long,short,byte,boolean,char,float";
+    
+    private Map getArgs(ProceedingJoinPoint joinPoint,String[] parameterNames) {
+    	Map allArgs = new HashMap();
+    	Object[] args = joinPoint.getArgs();
+    	 for (int k = 0; k < args.length; k++) {
+    	       Object arg = args[k];
+    	       if(arg==null) {
+    	    	   continue;
+    	       }
+    	       if(arg instanceof ServletResponse||arg instanceof ServletRequest) {//
+    	    	continue;   
+    	       }else if(arg instanceof MultipartFile) {//文件
+    	    	   allArgs.put(parameterNames[k],((MultipartFile)arg).getOriginalFilename());
+    	       }else if(arg instanceof MultipartFile[]) {//文件
+    	    	   allArgs.put(parameterNames[k],((MultipartFile[])arg).length);
+    	       }else if(arg instanceof Number||arg instanceof String||arg instanceof Character||arg instanceof Boolean) {//简单类型
+    	    	   allArgs.put(parameterNames[k],arg);
+    	       }else if(arg instanceof Collection) {//集合
+    	    	   allArgs.put(parameterNames[k],arg);
+    	       }else if(arg.getClass().isArray()) {//数组
+    	    	   allArgs.put(parameterNames[k],arg);
+    	       }else {//复杂类型
+    	    	   Map m = JacksonJsonUtils.readObject(JacksonJsonUtils.writeObject(arg), Map.class);
+    	    	   if(m!=null) {
+    	    		   allArgs.putAll(m);
+    	    	   }
+    	       }
+    	 }
+    	return allArgs;
+    }
+}
+

+ 30 - 27
common-base/src/main/java/com/factory/base/entity/task/PushWxMessage.java

@@ -1,43 +1,46 @@
 package com.factory.base.entity.task;
 
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import java.util.HashMap;
 import java.util.Map;
 
+import com.alibaba.fastjson.JSON;
+import com.factory.base.util.JacksonJsonUtils;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
 public class PushWxMessage {
-    private final static Logger LOGGER = LoggerFactory.getLogger(PushWxMessage.class);
 
     public static String sendMessage(AppEntry appinfo, TemplateEntry template) {
-        try {
-            Map params = new HashMap();
-            params.put("secret", appinfo.getSecret());
-            params.put("appid", appinfo.getAppId());
-            params.put("grant_type", "client_credential");
-            String result = HttpCilentUntil.httpGetToString(
-                    "https://api.weixin.qq.com/cgi-bin/token", params);
-            JSONObject jsonObject = JSON.parseObject(result);
-            String access_token = jsonObject.get("access_token").toString();
-            String pushUrl = new StringBuffer("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=").append(access_token).toString();
-            result = HttpCilentUntil.httpJsonToString(pushUrl, JSON.toJSONString(template));
-            jsonObject = JSON.parseObject(result);
-            String errCode = jsonObject.get("errcode").toString();
-            String errMsg = jsonObject.get("errmsg").toString();
-            System.out.println(errCode);
-            if (errCode != "0") LOGGER.error("下发微信消息错误code:{},errMsg{}", errCode, errMsg);
-            return errCode;
-        } catch (Throwable e) {
-            e.printStackTrace();
-            return "-1";
+		try {
+			Map<String,String> params = new HashMap<>();
+			params.put("secret", appinfo.getSecret());
+			params.put("appid", appinfo.getAppId());
+			params.put("grant_type", "client_credential");
+			String result = HttpCilentUntil.httpGetToString("https://api.weixin.qq.com/cgi-bin/token", params);
+			HashMap jsonObject = JacksonJsonUtils.readObject(result, HashMap.class);
+			log.info("下发微信消息TOKEN:{}", jsonObject);
+			String access_token = jsonObject.get("access_token").toString();
+			String pushUrl = new StringBuffer("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=")
+					.append(access_token).toString();
+			result = HttpCilentUntil.httpJsonToString(pushUrl, JacksonJsonUtils.writeObject(template));
+			jsonObject = JacksonJsonUtils.readObject(result, HashMap.class);
+			String errCode = jsonObject.get("errcode").toString();
+			String errMsg = jsonObject.get("errmsg").toString();
+			log.info("下发微信消息结果:{}", jsonObject);
+			if (!"0".equals(errCode)) {
+				log.error("下发微信消息错误code:{},errMsg:{}", errCode, errMsg);
+			}
+			return errCode;
+		} catch (Throwable e) {
+			log.error("下发微信消息错误",e);
+			return "-1";
         }
     }
 
     public static void main(String[] args) {
         AppEntry app = AppEntry.builder().appId("wxfd6e42e05b91163c").secret("7c4e39a33bf8b66beb919b9ad0a15832").build();
-        HashMap<String, ValEntry> dataMap = new HashMap();
+        HashMap<String, ValEntry> dataMap = new HashMap<>();
         dataMap.put("thing1", ValEntry.builder().value("this is one").build());
         dataMap.put("thing2", ValEntry.builder().value("this is two").build());
         dataMap.put("time3", ValEntry.builder().value("2021-07-23 20:00").build());

+ 285 - 0
common-base/src/main/java/com/factory/base/util/JacksonJsonUtils.java

@@ -0,0 +1,285 @@
+package com.factory.base.util;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.text.SimpleDateFormat;
+
+import org.springframework.util.NumberUtils;
+import org.springframework.util.StringUtils;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.core.JsonParser.Feature;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class JacksonJsonUtils {
+
+	private static final ObjectMapper objectMapper = new ObjectMapper();
+
+	
+	static {
+		//JsonReadFeature
+		objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // 设置日期解析格式
+		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 设置null值为不序列化
+		objectMapper.configure(Feature.ALLOW_COMMENTS, true);//可以解析C或者java 的注释
+		objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);//可以解析无双引号的
+		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//忽略位置字段
+		objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);// 忽略 transient 修饰的属性
+		SimpleModule simpleModule = new SimpleModule();
+	    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
+	    objectMapper.registerModule(simpleModule);//防止Long超出JS识别范围
+	}
+
+	public static ArrayNode getArrayNode() {
+		return objectMapper.createArrayNode();
+	}
+
+	public static ObjectNode getObjectNode() {
+		return objectMapper.createObjectNode();
+	}
+
+	/**
+	 * 通过path选择JsonNode 可能返回一个MissingNode
+	 * 
+	 * @param json {"name":"Jack","age":20,"class":["1","2","3"],"father":{"name":"old
+	 *             Jack","age":50}} father/name 可以选择到old Jack class/1 可以选举到"2"
+	 * @return
+	 * TypeReference<T> valueTypeRef
+	 * @throws Exception
+	 */
+	public static <T> T treeNodeToObject(JsonNode node, Class<T> classes) {
+		T result = null;
+		try {
+			if (node != null && !node.isMissingNode() && !node.isNull()) {
+				result = objectMapper.treeToValue(node, classes);
+			}
+		} catch (Exception e) {
+			log.error("treeNodeToObject error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 通过path选择JsonNode 可能返回一个MissingNode
+	 * 
+	 * @param json {"name":"Jack","age":20,"class":["1","2","3"],"father":{"name":"old
+	 *             Jack","age":50}} father/name 可以选择到old Jack class/2 可以选举到"2"
+	 * @return
+	 * @throws Exception
+	 */
+	public static JsonNode pathSelectNode(JsonNode node, String path) {
+		JsonNode result = node;
+		try {
+			if (!StringUtils.hasText(path)) {
+				return node;
+			}
+			String[] paths = StringUtils.split(path, "/");
+			for (String item : paths) {
+
+				Integer num = null;
+				try {
+					num = NumberUtils.parseNumber(item, Integer.class);
+				} catch (Exception e) {
+				}
+				if (num != null) {
+					result = result.path(num);
+				} else {
+					result = result.path(item);
+				}
+				if (result.isMissingNode() || result.isNull()) {
+					break;
+				}
+			}
+		} catch (Exception e) {
+			log.error("pathSelectNode error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将JSON串解析成JsonNode并获取路径下的节点
+	 * 
+	 * @param json JSON字符串
+	 * @return
+	 * @throws Exception
+	 */
+	public static JsonNode readTree(String json, String path) {
+		JsonNode result = null;
+		try {
+			result = pathSelectNode(objectMapper.readTree(json), path);
+		} catch (Exception e) {
+			log.error("parse json readTree error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将JSON串解析成JsonNode
+	 * 
+	 * @param json JSON字符串
+	 * @return
+	 * @throws Exception
+	 */
+	public static JsonNode readTree(String json) {
+		return readTree(json, null);
+	}
+
+	/**
+	 * 将JSON串解析成对象
+	 * 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(String json, Class<T> classes) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(json, classes);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+	/**
+	 * 将JSON串解析成对象
+	 * TypeReference<T> r = new TypeReference<T>(){} ; 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(String json,TypeReference<T> valueTypeRef) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(json, valueTypeRef);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将JSON串解析成对象
+	 * 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(File file, Class<T> classes) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(file, classes);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+	/**
+	 * 将JSON串解析成对象
+	 * 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(File file, TypeReference<T> valueTypeRef) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(file, valueTypeRef);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将JSON串解析成对象
+	 * 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(InputStream in, Class<T> classes) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(in, classes);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+	/**
+	 * 将JSON串解析成对象
+	 * 
+	 * @param json    JSON字符串
+	 * @param classes 对象类型
+	 * @return
+	 * @throws Exception
+	 */
+	public static <T> T readObject(InputStream in, TypeReference<T> valueTypeRef) {
+		T result = null;
+		try {
+			result = objectMapper.readValue(in, valueTypeRef);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将对象串解析成JSON字符串
+	 * 
+	 * @throws Exception
+	 */
+	public static String writeObject(Object object) {
+		String result = null;
+		try {
+			result = objectMapper.writeValueAsString(object);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+		return result;
+	}
+
+	/**
+	 * 将对象串写到文件
+	 * 
+	 * @throws Exception
+	 */
+	public static void writeObject(File file, Object object) {
+		try {
+			objectMapper.writeValue(file, object);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+	}
+
+	/**
+	 * 将对象串写到文件
+	 * 
+	 * @throws Exception
+	 */
+	public static void writeObject(OutputStream out, Object object) {
+		try {
+			objectMapper.writeValue(out, object);
+		} catch (Exception e) {
+			log.error("parse json object error:", e);
+		}
+	}
+}

+ 1 - 0
common-user/src/main/java/com/factory/user/config/AuthenticationInterceptor.java

@@ -62,6 +62,7 @@ public class AuthenticationInterceptor implements HandlerInterceptor {
             AuthUtils.writeJson(response, ResponseBeanBuilder.fail(ResponseEnum.AUTHENTICATION_EXPIRE));
             return false;
         }
+        request.setAttribute("UserId", checkResult.getData());
         //管理员不校验权限
         if (RemoteCommonConstants.ADMIN.equals(checkResult.getData())) {
             return true;