springboot日志切面通用類實例詳解
1.pom.xml文件導入AOP依賴
<!--aop依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>2.3.0.RELEASE</version> </dependency>
2.pom.xml導入Lombok依賴
<!--Lombok依賴--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
package jmu.rjc.aspect; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; //日志切面 @Aspect @Component public class LogAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); //包名配置為自己的項目包名即可 @Pointcut("execution(* jmu.rjc.web.*.*(..))") public void log(){} @Before("log()") public void doBefore(JoinPoint joinPoint){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String url = request.getRequestURL().toString(); String ip = request.getRemoteAddr(); String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); RequestLog requestLog = new RequestLog(url,ip,classMethod,args); logger.info("Request : {}",requestLog); } @After("log()") public void doAfter(){ logger.info("---------doAfter-------"); } @AfterReturning(returning = "result",pointcut = "log()") public void doAfterReturn(Object result){ logger.info("Result : {}"+result); } @Data @ToString @AllArgsConstructor @NoArgsConstructor private class RequestLog{ private String url; private String ip; private String classMethod; private Object[] args; } }
3.關於Lombok的註意點
Lombok的使用大大簡化瞭開發過程,提高瞭開發效率,但是也存在一些隱患.比如強行侵入jar包,JDK版本升級沖突,破壞部分封裝性等缺陷,使用前最好和團隊商量好
到此這篇關於springboot日志切面通用類的文章就介紹到這瞭,更多相關springboot日志切面通用類內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot開發教程之AOP日志處理
- SpringBoot使用AOP記錄接口操作日志詳解
- SpringBoot@Aspect 打印訪問請求和返回數據方式
- SpringBoot整合log4j日志與HashMap的底層原理解析
- SpringAop日志找不到方法的處理