瀏覽代碼

新增工具类,并且打印日志设置String最大值500个字符

liukx@elab 6 年之前
父節點
當前提交
3660e0811c

+ 31 - 0
elab-core/src/main/java/com/elab/core/utils/GzipUtils.java

@@ -0,0 +1,31 @@
+package com.elab.core.utils;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * @describe :压缩解压工具类
+ * @Author : liukx
+ * @time : 2019/2/26 - 16:33
+ */
+public class GzipUtils {
+
+    public static String unZip(byte[] b) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        ByteArrayInputStream in;
+        GZIPInputStream gunzip = null;
+
+        in = new ByteArrayInputStream(b);
+        gunzip = new GZIPInputStream(in);
+        byte[] buffer = new byte[256];
+        int n;
+        while ((n = gunzip.read(buffer)) >= 0) {
+            out.write(buffer, 0, n);
+        }
+        return out.toString();
+    }
+
+
+}

+ 19 - 0
elab-core/src/main/java/com/elab/core/utils/StringUtils.java

@@ -20,6 +20,7 @@ public class StringUtils {
     private static String localIp;
     private static DecimalFormat df = new DecimalFormat("##,###.00");
     private static NumberFormat nf = NumberFormat.getInstance();
+    private final static Integer maxStringLength = 500;
 
     public StringUtils() {
     }
@@ -620,4 +621,22 @@ public class StringUtils {
         return null;
     }
 
+    /**
+     * 字符串输出规则
+     *
+     * @param str
+     * @return
+     */
+    public static String logOut(String str) {
+        if (isEmpty(str)) {
+            return "null";
+        }
+
+        if (str.length() > maxStringLength) {
+            return str.substring(0, maxStringLength) + " 省略...";
+        }
+
+        return str;
+    }
+
 }

+ 2 - 1
elab-log/src/main/java/com/elab/log/asepct/CatAspect.java

@@ -8,6 +8,7 @@ import com.elab.core.bean.Info;
 import com.elab.core.exception.BusinessException;
 import com.elab.core.exception.CoreException;
 import com.elab.core.utils.ObjectUtils;
+import com.elab.core.utils.StringUtils;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.reflect.MethodSignature;
 import org.slf4j.Logger;
@@ -59,7 +60,7 @@ public class CatAspect {
             }
         }
         Transaction t = Cat.newTransaction(value, fullMethodName);
-        logger.info(" 开始执行方法 " + method.getName() + " 参数:" + JSON.toJSONString(pjp.getArgs()));
+        logger.info(" 开始执行方法 " + method.getName() + " 参数:" + StringUtils.logOut(JSON.toJSONString(pjp.getArgs())));
         try {
             proceed = pjp.proceed();
             t.setStatus(Transaction.SUCCESS);

+ 4 - 9
elab-log/src/main/java/com/elab/log/asepct/CatDaoAscept.java

@@ -3,13 +3,13 @@ package com.elab.log.asepct;
 import com.alibaba.fastjson.JSON;
 import com.dianping.cat.Cat;
 import com.dianping.cat.message.Transaction;
+import com.elab.core.utils.StringUtils;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.reflect.MethodSignature;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.lang.reflect.Method;
-import java.util.List;
 
 /**
  * DAO层执行拦截器
@@ -35,17 +35,12 @@ public class CatDaoAscept {
             Method objMethod = classTarget.getMethod(methodName, par);
 
             transaction = Cat.getProducer().newTransaction("SQL.Method", classTarget.getName().concat(".").concat(objMethod.getName()));
-            logger.debug(" 开始执行方法 " + method.getName() + " 参数:" + JSON.toJSONString(pjp.getArgs()));
+            logger.debug(" 开始执行方法 " + method.getName() + " 参数:" + StringUtils.logOut(JSON.toJSONString(pjp.getArgs())));
             proceed = pjp.proceed();
             if (proceed != null) {
-                if (proceed instanceof List) {
-                    List retValueList = (List) proceed;
-                    logger.debug("结束执行方法 " + method.getName() + " list 大小 : " + retValueList.size());
-                } else {
-                    logger.debug("结束执行方法 " + method.getName() + " 参数值 : " + JSON.toJSONString(proceed));
-                }
+                logger.debug("结束执行方法 " + method.getName() + " 参数值 : " + StringUtils.logOut(JSON.toJSONString(proceed)));
             } else {
-                logger.debug(" 结束执行方法 ... ");
+                logger.debug(" 结束执行方法 ... " + method.getName());
             }
             transaction.setStatus(Transaction.SUCCESS);
         } finally {

+ 12 - 10
elab-log/src/main/java/com/elab/log/asepct/LogResponseBodyAdvice.java

@@ -61,17 +61,19 @@ public class LogResponseBodyAdvice implements ResponseBodyAdvice {
     @Override
     public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
         try {
-            if (body instanceof Info) {
-                Info info = (Info) body;
-                String currentMessageId = Cat.getCurrentMessageId();
-                Map<String, Object> extension = info.getExtension();
-                if (extension == null) {
-                    extension = new HashMap<String, Object>(8);
-                    info.setExtension(extension);
+            if (body != null) {
+                if (body instanceof Info) {
+                    Info info = (Info) body;
+                    String currentMessageId = Cat.getCurrentMessageId();
+                    Map<String, Object> extension = info.getExtension();
+                    if (extension == null) {
+                        extension = new HashMap<String, Object>(8);
+                        info.setExtension(extension);
+                    }
+                    info.getExtension().put(this.logId, currentMessageId);
+                } else {
+                    BeanUtils.setProperty(body, this.logId, Cat.getCurrentMessageId());
                 }
-                info.getExtension().put(this.logId, currentMessageId);
-            } else {
-                BeanUtils.setProperty(body, this.logId, Cat.getCurrentMessageId());
             }
         } catch (Exception e) {
             logger.error("===========赋值参数出现故障==============", e);

+ 26 - 7
elab-spring/src/main/java/com/elab/spring/utils/RestTemplateUtils.java

@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.dianping.cat.Cat;
 import com.dianping.cat.message.Transaction;
 import com.elab.core.utils.ObjectUtils;
+import com.elab.core.utils.StringUtils;
 import com.elab.log.utils.CatMsgConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -12,6 +13,8 @@ import org.springframework.http.*;
 import org.springframework.http.client.SimpleClientHttpRequestFactory;
 import org.springframework.web.client.RestTemplate;
 
+import java.io.InputStream;
+
 /**
  * http调用工具
  *
@@ -70,12 +73,12 @@ public class RestTemplateUtils {
      * @param <T>
      * @return
      */
-    public <T> T post(String url, Object reqParam, Class<T> clazz)  {
+    public <T> T post(String url, Object reqParam, Class<T> clazz) {
         String newUrl = getUrl(url);
         Transaction t = Cat.getProducer().newTransaction(CatMsgConstants.THIRD_PARTY, newUrl);
         logger.info(" URL : " + url);
         if (reqParam != null) {
-            logger.info(" RequestData : " + logData(reqParam));
+            logger.info(" RequestData : " + StringUtils.logOut(logData(reqParam)));
         }
         T responseData = null;
         try {
@@ -83,9 +86,7 @@ public class RestTemplateUtils {
             HttpEntity<Object> entity = new HttpEntity<Object>(reqParam, headers);
             responseData = restTemplate.postForObject(url, entity, clazz);
             t.setStatus(Transaction.SUCCESS);
-            if (responseData != null) {
-                logger.info(" ResponseData : " + logData(responseData));
-            }
+            logResponse(responseData);
         } catch (Exception e) {
             logger.error("------ 第三方接口调用失败 : ", e);
             t.setStatus(e.getClass().getSimpleName());
@@ -95,6 +96,20 @@ public class RestTemplateUtils {
         return responseData;
     }
 
+    /**
+     * 通用的返回日志
+     *
+     * @param responseData
+     * @param <T>
+     */
+    private <T> void logResponse(T responseData) {
+        if (dontCareType(responseData)) {
+            logger.info(" 不关心的类型 ... ");
+        } else {
+            logger.info(" ResponseData : " + StringUtils.logOut(logData(responseData)));
+        }
+    }
+
     /**
      * get请求发送
      *
@@ -113,7 +128,7 @@ public class RestTemplateUtils {
             responseData = restTemplate.getForObject(url, clazz);
             t.setStatus(Transaction.SUCCESS);
             if (responseData != null) {
-                logger.info(" ResponseData : " + logData(responseData));
+                logResponse((T) responseData);
             }
         } catch (Exception e) {
             logger.error("------ 第三方接口调用失败 : ", e);
@@ -124,6 +139,10 @@ public class RestTemplateUtils {
         return responseData;
     }
 
+    private <T> boolean dontCareType(T responseData) {
+        return responseData instanceof byte[] || responseData instanceof InputStream;
+    }
+
     /**
      * 文件上传接口
      *
@@ -146,7 +165,7 @@ public class RestTemplateUtils {
             ResponseEntity<T> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, clazz);
             responseData = exchange.getBody();
             if (exchange != null && responseData != null) {
-                logger.info(" ResponseData : " + logData(responseData));
+                logger.info(" ResponseData : " + StringUtils.logOut(logData(responseData)));
             }
             t.setStatus(Transaction.SUCCESS);
         } catch (Exception e) {

+ 28 - 1
elab-spring/src/test/java/com/elab/spring/utils/RestTemplateUtilsTest.java

@@ -1,12 +1,21 @@
 package com.elab.spring.utils;
 
+import com.elab.core.utils.GzipUtils;
 import org.junit.Assert;
 import org.junit.Test;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.zip.GZIPInputStream;
 
 public class RestTemplateUtilsTest {
 
     private RestTemplateUtils restTemplateUtils = new RestTemplateUtils();
 
+    private RestTemplate restTemplate = new RestTemplate();
+
     @Test
     public void post() {
         String url = "http://106.14.133.2:5555/elab-marketing-authentication//ipAddr/getIpAddr";
@@ -22,8 +31,26 @@ public class RestTemplateUtilsTest {
         System.out.println("--->" + get);
         Assert.assertNotNull(get);
     }
+    public static String conventFromGzip(String str) throws IOException {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        ByteArrayInputStream in;
+        GZIPInputStream gunzip = null;
 
-    public void postUpload() {
+        in = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
+        gunzip = new GZIPInputStream(in);
+        byte[] buffer = new byte[256];
+        int n;
+        while ((n = gunzip.read(buffer)) >= 0) {
+            out.write(buffer, 0, n);
+        }
+        return out.toString();
+    }
+    @Test
+    public void getInputstream() throws IOException {
+        String url = "http://wthrcdn.etouch.cn/weather_mini?city=上海";
+        byte[] bytes = restTemplateUtils.get(url, byte[].class);
+        String s1 = GzipUtils.unZip(bytes);
+        System.out.println(s1);
 
     }
 }