Spring Boot:(四)統一日誌處理

並非只針對Spring Boot,如果你的項目用的是Spring MVC,做下簡單的轉換即可在你的項目中實現相同的功能

日誌管理的實現

思路:

    在Service層中,涉及到大量業務邏輯操作,我們往往就需要在一個業務操作完成後(不管成敗或失敗),生成一條日誌,並插入到數據庫中。那麼我們可以在這些涉及到業務操作的方法上使用一個自定義註解進行標記,同時將日誌記錄到註解中。再配合Spring的AOP功能,在監聽到該方法執行之後,獲取到註解內的日誌信息,把這條日誌插入到數據即可。

1、自定義註解

這裏我們自定義一個日誌註解,該註解中的logStr屬性將用來保存日誌信息。自定義註解代碼如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface Log {
    String logStr() default "";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、使用自定義註解

接着就是到Service層中,在需要使用到日誌功能的方法上加上該註解。如果業務需求是在添加一個用戶之後,記錄一條日誌,那只需要在添加用戶的方法上加上這個自定義註解即可。代碼如下:

@Service
public class UserService {

    @Log(logStr = "添加一個用戶")
    public Result add(User user) {
        return ResultUtils.success();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3、使用AOP統一處理日誌

前面的自定義註解只是起到一個標記與存儲日誌的作用,接下來需要就該使用Spring的AOP功能,攔截方法的執行,通過反射獲取到註解及註解中所包含的日誌信息。

如果你不清楚怎麼在Spring Boot中使用AOP功能,建議你去看上一篇文章

因爲代碼量不大,就不多廢話了,直接貼出日誌切面的完整代碼,詳細情況看代碼中的註釋:


@Component
@Aspect
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // 設置切點表達式
    @Pointcut("execution(* com.lqr.service..*(..))")
    private void pointcut() {
    }

    // 方法後置切面
    @After(value = "pointcut()")
    public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {
        // 拿到切點的類名、方法名、方法參數
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        // 反射加載切點類,遍歷類中所有的方法
        Class<?> targetClass = Class.forName(className);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            // 如果遍歷到類中的方法名與切點的方法名一致,並且參數個數也一致,就說明切點找到了
            if (method.getName().equalsIgnoreCase(methodName)) {
                Class<?>[] clazzs = method.getParameterTypes();
                if (clazzs.length == args.length) {
                    // 獲取到切點上的註解
                    Log logAnnotation = method.getAnnotation(Log.class);
                    if (logAnnotation != null) {
                        // 獲取註解中的日誌信息,並輸出
                        String logStr = logAnnotation.logStr();
                        logger.error("獲取日誌:" + logStr);
                        // 數據庫記錄操作...
                        break;
                    }
                }
            }
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

4、驗證

爲了驗證這種方式是否真的能拿到註解中攜帶的日誌信息,這裏創建一個Controller,代碼如下:

@RestController
public class UserController {

    @Autowired
    UserService mUserService;

    @PostMapping("/add")
    public Result add(User user) throws NotFoundException {
        return mUserService.add(user);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

使用postman訪問接口,可以看到註解中的日誌信息確實被拿到了。

你以爲這樣就結束了嗎?不,這僅僅只是實現了日誌功能,但稱不上優雅,因爲存在不方便的地方,下面就說下,如何對這種方式進一步優化,從而做到優雅的處理日誌功能。

三、優化日誌功能

1、分析

前面確確實實的使用自定義註解和AOP做到了日誌功能,但存在什麼問題呢?這個問題不是代碼問題,而是業務功能問題。開發中可能有以下幾種情況:

  1. 假設公司的業務是不僅僅只是記錄某個用戶使用該系統做了什麼操作,還需要記錄在操作的過程中出現過什麼問題。
  2. 假設日誌的內容,不可以在註解中寫死,要可以在代碼中自由設置日誌信息。

簡而言之,就是日誌內容可以在代碼中隨意修改。這就有問題了,註解是靜態侵入的,要怎麼才能做到在代碼中動態修改註解中的屬性值呢?所幸,javassist可以幫我們做到這一點,下面就來看看,如果實現該功能。

javassist需要自己導入第三方依賴,如果你項目有使用到Spring Boot的模板功能(thymeleaf),則無須添加依賴。

2、完善與增強

1)封裝AnnotationUtils

結合網上查閱到的資料,我對使用javassist動態修改方法上註解及查看註解中屬性值的功能做了一個封裝,工具類名爲:AnnotationUtils(和Spring自帶的一個類名字一樣,注意不要在代碼中導錯包了),並使用了單例模式。代碼如下:

/** 
 * @描述 註解中屬性修改、查看工具
 */
public class AnnotationUtils {

    private static AnnotationUtils mInstance;

    public AnnotationUtils() {
    }

    public static AnnotationUtils get() {
        if (mInstance == null) {
            synchronized (AnnotationUtils.class) {
                if (mInstance == null) {
                    mInstance = new AnnotationUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * 修改註解上的屬性值
     *
     * @param className  當前類名
     * @param methodName 當前方法名
     * @param annoName   方法上的註解名
     * @param fieldName  註解中的屬性名
     * @param fieldValue 註解中的屬性值
     * @throws NotFoundException
     */
    public void setAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName, String fieldValue) throws NotFoundException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass ct = classPool.get(className);
        CtMethod ctMethod = ct.getDeclaredMethod(methodName);
        MethodInfo methodInfo = ctMethod.getMethodInfo();
        ConstPool constPool = methodInfo.getConstPool();
        AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        Annotation annotation = attr.getAnnotation(annoName);
        if (annotation != null) {
            annotation.addMemberValue(fieldName, new StringMemberValue(fieldValue, constPool));
            attr.setAnnotation(annotation);
            methodInfo.addAttribute(attr);
        }
    }

    /**
     * 獲取註解中的屬性值
     *
     * @param className  當前類名
     * @param methodName 當前方法名
     * @param annoName   方法上的註解名
     * @param fieldName  註解中的屬性名
     * @return
     * @throws NotFoundException
     */
    public String getAnnotatioinFieldValue(String className, String methodName, String annoName, String fieldName) throws NotFoundException {
        ClassPool classPool = ClassPool.getDefault();
        CtClass ct = classPool.get(className);
        CtMethod ctMethod = ct.getDeclaredMethod(methodName);
        MethodInfo methodInfo = ctMethod.getMethodInfo();
        AnnotationsAttribute attr = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
        String value = "";
        if (attr != null) {
            Annotation an = attr.getAnnotation(annoName);
            if (an != null)
                value = ((StringMemberValue) an.getMemberValue(fieldName)).getValue();
        }
        return value;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

2)封裝LogUtils

通過上面的工具類(AnnotationUtils)雖然可以實現在代碼中動態修改註解中的屬性值的功能,但AnnotationUtils方法中需要的參數過多,這裏對其做一層封裝,不需要在代碼中考慮類名、方法名的獲取,方便開發。

/** 
 * @描述 日誌修改工具
 */
public class LogUtils {

    private static LogUtils mInstance;

    private LogUtils() {
    }

    public static LogUtils get() {
        if (mInstance == null) {
            synchronized (LogUtils.class) {
                if (mInstance == null) {
                    mInstance = new LogUtils();
                }
            }
        }
        return mInstance;
    }

    public void setLog(String logStr) throws NotFoundException {
        String className = Thread.currentThread().getStackTrace()[2].getClassName();
        String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
        AnnotationUtils.get().setAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr", logStr);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

3)Service中根據情況動態修改日誌信息

@Service
public class UserService {

    @Log(logStr = "添加一個用戶")
    public Result add(User user) throws NotFoundException {
        if (user.getAge() < 18) {
            LogUtils.get().setLog("添加用戶失敗,因爲用戶未成年");
            return ResultUtils.error("未成年不能註冊");
        }
        if ("男".equalsIgnoreCase(user.getSex())) {
            LogUtils.get().setLog("添加用戶失敗,因爲用戶是個男的");
            return ResultUtils.error("男性不能註冊");
        }

        LogUtils.get().setLog("添加用戶成功,是一個" + user.getAge() + "歲的美少女");

        return ResultUtils.success();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

4)修改日誌切面

使用javassist修改過的註解屬性值無法通過java反射正確靜態獲取,還需要藉助javassist來動態獲取,所以,LogAspect中的代碼修改如下:

@Component
@Aspect
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* com.lqr.service..*(..))")
    private void pointcut() {
    }

    @After(value = "pointcut()")
    public void After(JoinPoint joinPoint) throws NotFoundException, ClassNotFoundException {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String logStr = AnnotationUtils.get().getAnnotatioinFieldValue(className, methodName, Log.class.getName(), "logStr");
        if (!StringUtils.isEmpty(logStr)) {
            logger.error("獲取日誌:" + logStr);
            // 數據庫記錄操作...
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3、驗證

上面代碼都編寫完了,下面就驗證下,是否可以根據業務情況動態註解中的屬性值吧。

https://github.com/zhaoyulonggit/AopLog.git


發佈了71 篇原創文章 · 獲贊 14 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章