Spring Boot 通過切面打日誌

上次聊得spring 打日誌 https://blog.csdn.net/u013476435/article/details/81984605

主要是通過 實現 MethodInterceptor 來實現的. 但是在Spring  Boot, 註解的方式 更加低耦合 直接貼代碼了.

 

package com.xxx.developer.service.config;

import com.alibaba.fastjson.JSON;
import com.xxx.common.annotation.NotNeedLog;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * @author 作者<LiuQi>
 * @ClassName: MethodLogAdvice
 * @Description: 自動打日誌切面, 會自動將所切面的日誌打印到控制檯 以便於調試
 * @date 2019年09月17日 10:13:07
 * <p>
 * 禁止使用格式化格式代碼
 */
@Aspect
@Component
public class MethodLogAdvice {
    /**
     * @Fields : 字段最長輸出設置,爲了避免字符太長而刷屏
     */
    public final Integer subLogLength = 3000;

    /**
     * @Fields : 環境設置
     */
    @Value("${spring.profiles.active}")
    private String environmentModel;

    /**
     * 攔截要執行的目標方法
     * <p>
     * 這裏主要攔截 controller 以及 service 方法
     */
    @Around("   execution(* com.jeejio.developer.service.*.controller..*(..))" +
            "|| execution(* com.jeejio.developer.service.*.service..*(..))")
    public Object joinpointMethod(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            StopWatch clock = new StopWatch();
            clock.start(); //計時開始
            //得到返回結果
            result = joinPoint.proceed();
            clock.stop();  //計時結束

            //只有才dev 和local 纔打印日誌
            if ("dev".equals(environmentModel) || "local".equals(environmentModel)) {
                //太長的返回結果 予以過濾後返回
                String resultJson = JSON.toJSONString(result);
                Method method = null;
                //通過父親得到孩子的方法 得到其 註解
                Class<?>[] objects = Arrays.stream(joinPoint.getArgs()).map(Object::getClass).toArray(Class[]::new);
                method = joinPoint.getSourceLocation().getWithinType().getDeclaredMethod(joinPoint.getSignature().getName(), objects);
                if (null != method) {
                    NotNeedLog notNeedLog = method.getAnnotation(NotNeedLog.class);
                    if (null != notNeedLog && notNeedLog.closeLogStatus()) {
                        //如果爲true  那麼就不需要打印日誌
                        return result;
                    }
                }
                //方法參數類型,轉換成簡單類型
                LoggerFactory.getLogger(joinPoint.getTarget().getClass()).info(
                        "耗時" + clock.getTotalTimeSeconds() + "秒|" + joinPoint.getSignature().getName() +
                                "|參數:" + JSON.toJSONString(joinPoint.getArgs()) +
                                " 結果:" + (StringUtils.isNotEmpty(resultJson) && resultJson.length() > subLogLength ?
                                resultJson.substring(0, subLogLength) + "......(已省略" + (resultJson.length() - subLogLength) + "個字符)"
                                : resultJson)
                );
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

}

效果如下 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章