SpringBoot + AOP + 自定義註解實現統一日誌處理

SpringBoot + AOP + 自定義註解實現統一日誌處理

在實際開發中,我們經常需要對接口方法打印出日誌,比如參數等。如果每個方法裏都要手動去寫,那樣代碼顯得太冗餘了,而且日誌風格也參差不齊。
本文將使用Spring Boot、Spring AOP結合自定義註解,實現統一的日誌處理。

添加依賴

因爲我將會使用json序列化,所以加入了fastjson的依賴.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>

主啓動類

如果使用Spring Initializr生成項目,則無須手動編寫。

@SpringBootApplication
public class SpringBootAopApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootAopApplication.class, args);
    }
}

編寫註解

@Retention(RetentionPolicy.RUNTIME) // 運行時有效
@Target(ElementType.METHOD) // 定義在方法上
@Documented
public @interface ShowLog {
    String value() default "";
}

編寫Aspect

使用@Aspect註解聲明是一個切面,並且使用@Component註解加入到IoC容器中。

@Aspect
@Component
@Slf4j
public class AnnotationLogAspect {

    @Pointcut("execution(public * com.xudc.springboot.web.*.*(..))")
    public void aopLog(){
    }

    @Before("aopLog() && @annotation(showLog)")
    public void doBefore(JoinPoint joinPoint, ShowLog showLog) {
        Object[] args = joinPoint.getArgs();
        log.info("參數={}", JSON.toJSONString(args));
        Signature signature = joinPoint.getSignature();
        log.info("方法={}", signature.getName());
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuffer url = request.getRequestURL();
        log.info("請求地址={}", url);

        Map<String, Object> params = new HashMap<>(16);
        request.getParameterMap().forEach((key, values) -> {
            if (values.length == 1) {
                params.put(key, values[0]);
            } else {
                params.put(key, values);
            }
        });
        log.info("請求參數={}", JSON.toJSONString(params));
        log.info("註解value={}", showLog.value());
    }
}

編寫接口

@RestController
public class TestController {

    @GetMapping("/test/{id}")
    @ShowLog("輸出日誌")
    public String test(@PathVariable String id, @RequestParam(required = false) String name){
        return "success";
    }
}

詳細代碼

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