怎樣使用自定義註解和AOP實現日誌記錄 -學習筆記

1、自定義註解

package com.dh1027.login.annotation;

import java.lang.annotation.*;

/**
 * 日誌註解
 * Created by heyj2 on 2018/7/12.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DHLog {
    public String logDescription();
}

2、日誌切面

package com.dh1027.login.annotation;

import com.dh1027.login.controller.LoginController;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 日誌記錄切面
 * Created by heyj2 on 2018/7/12.
 */
@Aspect
@Component
public class LoggerAdvice {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Pointcut("execution(public * com.dh1027.login..*(..))")
    public void webLog() {
    }

    @Before("webLog() && @annotation(loggerManage)")
    public void addBeforeLogger(JoinPoint joinPoint, DHLog loggerManage) {
        LocalDateTime now = LocalDateTime.now();

        logger.info(now.toString()+"執行[" + loggerManage.logDescription() + "]開始");
        logger.info("執行的方法["+joinPoint.getSignature().toString()+"]");

        logger.info("參數["+parseParames(joinPoint.getArgs())+"]");

    }

    @AfterReturning(pointcut = "webLog() && @annotation(loggerManage)")
    public void addAfterReturningLogger(JoinPoint joinPoint, DHLog loggerManage) {
        LocalDateTime now = LocalDateTime.now();
        logger.info(now.toString()+"執行 [" + loggerManage.logDescription() + "] 結束");
    }

    @AfterThrowing(pointcut = "webLog() && @annotation(loggerManage)", throwing = "ex")
    public void addAfterThrowingLogger(JoinPoint joinPoint, DHLog loggerManage, Exception ex) {
        LocalDateTime now = LocalDateTime.now();
        logger.error(now.toString()+"執行 [" + loggerManage.logDescription() + "] 異常", ex);
    }

    private String parseParames(Object[] parames) {

        if (null == parames || parames.length <= 0) {
            return "";

        }
        StringBuffer param = new StringBuffer("傳入參數 # 個:[ ");
        int i =0;
        for (Object obj : parames) {
            i++;
            if (i==1){
                param.append(obj.toString());
                continue;
            }
            param.append(" ,").append(obj.toString());
        }
        return param.append(" ]").toString().replace("#",String.valueOf(i));
    }

}

3、測試使用

package com.dh1027.login.controller;

import com.dh1027.login.annotation.DHLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by heyj2 on 2018/6/5.
 */
@RestController
public class HelloWorldController {
    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("/hello")
    @DHLog(logDescription = "測試註解......")
    public String index() {
        logger.info("-----Hello World--------");
        return "Hello World";
    }
}

各種IT書籍書目及下載鏈接
https://blog.csdn.net/dh1027/article/details/89327978

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