SpringBoot詳解(四)-優雅地處理日誌

SpringBoot詳解系列文章:
SpringBoot詳解(一)-快速入門
SpringBoot詳解(二)-Spring Boot的核心
SpringBoot詳解(三)-Spring Boot的web開發
SpringBoot詳解(四)-優雅地處理日誌java

1、簡介

日誌功能在j2ee項目中是一個至關常見的功能,在一個小項目中或許你能夠在一個個方法中,使用日誌表的Mapper生成一條條的日誌記錄,但這無非是最爛的作法之一,由於這種作法會讓日誌Mapper分佈到了項目的多處代碼中,後續很難管理。而對於大型的項目而言,這種作法根本不能採用。本篇文章將介紹,使用自定義註解,配合AOP,優雅的完成日誌功能。git

本文Demo使用的是Spring Boot框架,但並不是只針對Spring Boot,若是你的項目用的是Spring MVC,作下簡單的轉換便可在你的項目中實現相同的功能。github

2、日誌管理的實現

在開始編碼以前,先介紹下思路:web

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

好了,下面就對上面的理論付出實踐。bash

一、自定義註解

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface Log {
    String logStr() default "";
}複製代碼

二、使用自定義註解

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

@Service
public class UserService {

    @Log(logStr = "添加一個用戶")
    public Result add(User user) {
        return ResultUtils.success();
    }
}複製代碼

三、使用AOP統一處理日誌

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

若是你不清楚怎麼在Spring Boot中使用AOP功能,建議你去看上一篇文章:SpringBoot詳解(三)-Spring Boot的web開發,這裏再也不贅訴。post

由於代碼量不大,就很少廢話了,直接貼出日誌切面的完整代碼,詳細狀況看代碼中的註釋:

@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;
                    }
                }
            }
        }
    }

}複製代碼

四、驗證

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

@RestController
public class UserController {

    @Autowired
    UserService mUserService;

    @PostMapping("/add")
    public Result add(User user) throws NotFoundException {
        return mUserService.add(user);
    }
}複製代碼

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

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

3、優化日誌功能

一、分析

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

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

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

javassist須要本身導入第三方依賴,若是你項目有使用到Spring Boot的模板功能(thymeleaf),則無須添加依賴。

二、完善與加強

1)封裝AnnotationUtils

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

/**
 * @建立者 CSDN_LQR
 * @描述 註解中屬性修改、查看工具
 */
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;
    }

}複製代碼

2)封裝LogUtils

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

/**
 * @建立者 CSDN_LQR
 * @描述 日誌修改工具
 */
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);
    }
}複製代碼

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();
    }

}複製代碼

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);
            // 數據庫記錄操做...
        }
    }
}複製代碼

三、驗證

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

最後提供下Demo地址

github.com/GitLqr/Aspe…

相關文章
相關標籤/搜索