用SpringBoot搭建個人博客01-----使用AOP統一處理Web請求日誌

摘要

AOP 是面向切面的編程,就是在運行期通過動態代理的方式對代碼進行增強處理,比較核心的概念有 切點,切面,通知,有關AOP的詳情參考:。
本文要介紹的是在一個SpringBoot項目中如何統一的處理Web請求日誌,基本思想還是採用AOP的方式,攔截請求,然後,寫入日誌。

相關依賴

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

項目引入spring-boot-starter-web 依賴之後無需在引入相關的日誌依賴,因爲spring-boot-starter-web中已經集成了slf4j 的依賴。
引入spring-boot-starter-aop 依賴之後,AOP 的功能即是啓動狀態,無需在添加@EnableAspectJAutoProxy註解。
在這裏插入圖片描述
在這裏插入圖片描述

定義系統日誌註解

/**
 * 系統日誌註解
 * Created by xiang.wei on 2018/10/17
 *
 * @author xiang.wei
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    String value() default "";
}

定義切面

@Aspect
@Component
public class SysLogAspect {
    private Logger logger = LoggerFactory.getLogger(SysLogAspect.class);
//    @Autowired
//    private MtoLogService mtoLogService;

    /**
     * 定義日誌切點
     */
    @Pointcut("@annotation(com.jay.common.annotation.SysLog)")
    public void logPointCut() {

    }

    /**
     * 環繞通知
     * @param point
     * @return
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object proceed = point.proceed();
//        執行時長
        long time = System.currentTimeMillis() - startTime;
        saveSysLog(point, time);
        return proceed;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MtoLog mtoLog = new MtoLog();
//      獲取註解內容
        SysLog annotation = method.getAnnotation(SysLog.class);
        if (annotation != null) {
            mtoLog.setOperation(annotation.value());
        }
//        獲取類名
        String className = joinPoint.getTarget().getClass().getName();
//        獲取方法名
        String methodName = method.getName();
        mtoLog.setMethod(className + "." + methodName + "()");
//       獲取參數
        Object[] args = joinPoint.getArgs();
        if (args != null) {
            String param = JSON.toJSONString(args[0]);
            mtoLog.setParams(param);
        }
        mtoLog.setTime(time);
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        mtoLog.setIp(IpUtil.getIpAddr(request));

        mtoLog.setCreateDate(new Date());
        logger.info("請求的參數="+JSON.toJSONString(mtoLog));
//        mtoLogService.insert(mtoLog);
    }
}

使用

  @SysLog("登錄接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String username,String password,
                        @RequestParam(value = "rememberMe", defaultValue = "0") int rememberMe,
                        ModelMap model) {
。。。。
}

運行效果:
在這裏插入圖片描述

參考博客

http://blog.didispace.com/springbootaoplog/

代碼地址

https://github.com/XWxiaowei/JayBlog/tree/v3-logback-validation

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