1. 程式人生 > >列印dubbo介面所有請求資料日誌

列印dubbo介面所有請求資料日誌

import com.ctl.util.StringUtil;
import net.sf.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * <p>Title: DubboServiceAspect</p>
 * <p>Description: 列印dubbo服務請求資料</p>
 * <p>Copyright: Copyright (c) 2018</p>
 * @version 1.0
 * @date 2018-11-09 13:07
 */
public class DubboServiceAspect {
    private Logger logger = LoggerFactory.getLogger(DubboServiceAspect.class);
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();
        Object classNameAndMethodName = proceedingJoinPoint.toString();
        StringBuilder queryJson = new StringBuilder();
        if (args != null && args.length > 0) {
            try {
                queryJson.append(StringUtil.formatJson(JSONObject.fromObject(args[0]).toString())).append("\n");
            } catch (Exception e) {
            }
//            for (int i = 1; i < args.length; i++) {
//                if (args[i].getClass().getSimpleName().startsWith("java")) {
//                    queryJson.append("\targs[").append(i).append("]=").append(args[i]).append("\t");
//                }
//            }
            logger.info("classNameAndMethodName={},\tqueryJson={}", classNameAndMethodName, queryJson);
        }
        return proceedingJoinPoint.proceed();

    }

}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
   <bean id="dubboServuceAspect" class="com.*.aspect.DubboServiceAspect" />
   <!--統一驗證小程式呼叫介面時是否帶有合法的securityKey,合法則繼續走,不合法則直接攔截-->
   <aop:config>
      <aop:aspect id="dubboServuce" ref="dubboServuceAspect" order="1">
         <!-- 配置一個切點 -->
         <aop:pointcut id="dubboServucePoint" expression="execution(* com.*.*.service.impl.*.*(..))"  />
         <aop:around method="around" pointcut-ref="dubboServucePoint"/>
      </aop:aspect>
   </aop:config>
</beans>

 StringUtil.java

public class StringUtil {
    private static Logger logger = LoggerFactory.getLogger(StringUtil.class);
    public static JsonConfig jsonConfig = null;

    static {
        jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Timestamp.class, new JsonDateValueProcessor());
        jsonConfig.registerJsonValueProcessor(Integer.class, new JsonNumberValueProcessor());
        jsonConfig.registerJsonValueProcessor(Long.class, new JsonNumberValueProcessor());
        jsonConfig.registerJsonValueProcessor(Byte.class, new JsonNumberValueProcessor());
        jsonConfig.registerJsonValueProcessor(Float.class, new JsonNumberValueProcessor());
        jsonConfig.registerJsonValueProcessor(Double.class, new JsonNumberValueProcessor());
    }
    /**
     * 單位縮排字串。
     */
    private static String SPACE = "   ";
    private static String NEWLINE="\n";
    /**
     * 判斷是否為空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * 判斷是否為空去除空字元
     * @param str
     * @return
     */
    public static boolean isEmptyTrim(String str) {
        return str == null || str.trim().length() == 0;
    }

    /**
     * 判斷字串陣列是否為空
     * @param str
     * @return
     */
    public static boolean isEmpty(String[] str) {
        return str == null || str.length == 0;
    }
    /**
     * sql防止注入替換
     * @param paramStr
     * @return
     */
    public static  String sqlResplace(String paramStr) {
        if (StringUtil.isEmptyTrim(paramStr)) {
            logger.info("sqlResplace={}為空", paramStr);
            return null;
        } else {
            logger.info("sqlResplace={}", paramStr);
        }
        StringBuilder strDest = new StringBuilder();
        for (int i = 0; i < paramStr.length(); i++) {
            char ch = paramStr.charAt(i);
            switch (ch) {
                case '\0':
                    strDest.append("\\0");
                    break;
                case '\n':
                    strDest.append("\\n");
                    break;
                case '\r':
                    strDest.append("\\r");
                    break;
                case '\'':
                    strDest.append("\\'");
                    break;
                case '"':
                    strDest.append("\\\"");
                    break;
                case '\\':
                    strDest.append("\\\\");
                    break;
                case '%':
                    strDest.append("\\%");
                    break;
                case '_':
                    strDest.append("\\_");
                    break;
                default:
                    strDest.append(ch);
                    break;
            }
        }
        return strDest.toString();
    }

    /**
     * 返回格式化JSON字串。
     *
     * @param json 未格式化的JSON字串。
     * @return 格式化的JSON字串。
     */
    public static String formatJson(String json) {
        if (StringUtil.isEmptyTrim(json)) {
            logger.info("json={}為空", json);
            return null;
        }
        try {
            StringBuffer result = new StringBuffer();

            int length = json.length();
            int number = 0;
            char key = 0;

            //遍歷輸入字串。
            for (int i = 0; i < length; i++) {
                //1、獲取當前字元。
                key = json.charAt(i);

                //2、如果當前字元是前方括號、前花括號做如下處理:
                if ((key == '[') || (key == '{')) {
                    //(1)如果前面還有字元,並且字元為“:”,列印:換行和縮排字元字串。
                    if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                        result.append(NEWLINE);
                        result.append(indent(number));
                    }

                    //(2)列印:當前字元。
                    result.append(key);

                    //(3)前方括號、前花括號,的後面必須換行。列印:換行。
                    result.append(NEWLINE);

                    //(4)每出現一次前方括號、前花括號;縮排次數增加一次。列印:新行縮排。
                    number++;
                    result.append(indent(number));

                    //(5)進行下一次迴圈。
                    continue;
                }

                //3、如果當前字元是後方括號、後花括號做如下處理:
                if ((key == ']') || (key == '}')) {
                    //(1)後方括號、後花括號,的前面必須換行。列印:換行。
                    result.append(NEWLINE);

                    //(2)每出現一次後方括號、後花括號;縮排次數減少一次。列印:縮排。
                    number--;
                    result.append(indent(number));

                    //(3)列印:當前字元。
                    result.append(key);

                    //(4)如果當前字元後面還有字元,並且字元不為“,”,列印:換行。
                    if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                        result.append(NEWLINE);
                    }

                    //(5)繼續下一次迴圈。
                    continue;
                }

                //4、如果當前字元是逗號。逗號後面換行,並縮排,不改變縮排次數。
                if ((key == ',')) {
                    result.append(key);
                    result.append(NEWLINE);
                    result.append(indent(number));
                    continue;
                }

                //5、列印:當前字元。
                result.append(key);
            }

            return result.toString();
        } catch (Exception e) {
            logger.error("格式化jsonStr失敗:" + json, e);
            return json;
        }
    }

    /**
     * 返回指定次數的縮排字串。每一次縮排三個空格,即SPACE。
     *
     * @param number 縮排次數。
     * @return 指定縮排次數的字串。
     */
    private static String indent(int number) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < number; i++) {
            result.append(SPACE);
        }
        return result.toString();
    }
    /**
     * 根據imgUrl獲取imgPath失敗
     * @param imgUrl
     * @return
     */
    public static String imagePath(String imgUrl) {
        String imageUrlPath = "";
        try {
            if(isEmptyTrim(imgUrl)){
                return null;
            }
            int index = -1;
//            switch (imgUrl) {
//                case "http://":
//                    index = imgUrl.indexOf("/", 7);
//                    if (index > 0) {
//                        imageUrlPath = imgUrl.substring(index + 1);
//                        logger.info("imageUrl={},imageUrlPath={}", imgUrl, imageUrlPath);
//                    }
//                    break;
//                case "https://":
//                    index = imgUrl.indexOf("/", 8);
//                    if (index > 0) {
//                        imageUrlPath = imgUrl.substring(index + 1);
//                        logger.info("imageUrl={},imageUrlPath={}", imgUrl, imageUrlPath);
//                    }
//                    break;
//                default:
//                    imageUrlPath = imgUrl;
//                    break;
//            }
            if (imgUrl.startsWith("http://")) {
                index = imgUrl.indexOf("/", 7);
                if (index > 0) {
                    imageUrlPath = imgUrl.substring(index + 1);
                    logger.info("imageUrl={},imageUrlPath={}", imgUrl, imageUrlPath);
                }
            }
            if (imgUrl.startsWith("https://")) {
                index = imgUrl.indexOf("/", 8);
                if (index > 0) {
                    imageUrlPath = imgUrl.substring(index + 1);
                    logger.info("imageUrl={},imageUrlPath={}", imgUrl, imageUrlPath);
                }
            }
            if(!imgUrl.startsWith("http://")&&!imgUrl.startsWith("https://")){
                imageUrlPath = imgUrl;
            }
            return imageUrlPath;
        } catch (Exception e) {
            logger.error("根據imgUrl獲取imgPath失敗",e);
        }
        return imageUrlPath;
    }

    public static void main(String[] args) {
         
    }
}