版權聲明:本文爲博主原創文章,歡迎轉載,轉載請註明做者、原文超連接java
本文主要記錄如何使用aop切面的方式來實現日誌記錄功能。web
主要記錄的信息有: 操做人,方法名,參數,運行時間,操做類型(增刪改查),詳細描述,返回值。redis
這裏只有兩個配置:
1)server.port=11000,設置項目啓動的端口號,防止被其餘服務佔用;
2)spring.aop.auto=true,開啓spring的aop配置,簡單明瞭,不須要多配置其餘的配置或註解。
application.yml文件
server: port: 11000 spring: aop: auto: true #啓動aop配置
這個是最主要的類,可使用自定義註解或針對包名實現AOP加強。spring
1)這裏實現了對自定義註解的環繞加強切點,對使用了自定義註解的方法進行AOP切面處理;apache
2)對方法運行時間進行監控;json
3)對方法名,參數名,參數值,對日誌描述的優化處理;數組
在方法上增長@Aspect 註解聲明切面,使用@Pointcut 註解定義切點,標記方法。springboot
使用切點加強的時機註解:@Before,@Around,@AfterReturning,@AfterThrowing,@Afterapp
package com.wwj.springboot.aop; import com.alibaba.fastjson.JSON; import com.wwj.springboot.annotation.OperationLogDetail; import com.wwj.springboot.model.OperationLog; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ @Aspect @Component public class LogAspect { /** * 此處的切點是註解的方式,也能夠用包名的方式達到相同的效果 * '@Pointcut("execution(* com.wwj.springboot.service.impl.*.*(..))")' */ @Pointcut("@annotation(com.wwj.springboot.annotation.OperationLogDetail)") public void operationLog(){} /** * 環繞加強,至關於MethodInterceptor */ @Around("operationLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { Object res = null; long time = System.currentTimeMillis(); try { res = joinPoint.proceed(); time = System.currentTimeMillis() - time; return res; } finally { try { //方法執行完成後增長日誌 addOperationLog(joinPoint,res,time); }catch (Exception e){ System.out.println("LogAspect 操做失敗:" + e.getMessage()); e.printStackTrace(); } } } private void addOperationLog(JoinPoint joinPoint, Object res, long time){ MethodSignature signature = (MethodSignature)joinPoint.getSignature(); OperationLog operationLog = new OperationLog(); operationLog.setRunTime(time); operationLog.setReturnValue(JSON.toJSONString(res)); operationLog.setId(UUID.randomUUID().toString()); operationLog.setArgs(JSON.toJSONString(joinPoint.getArgs())); operationLog.setCreateTime(new Date()); operationLog.setMethod(signature.getDeclaringTypeName() + "." + signature.getName()); operationLog.setUserId("#{currentUserId}"); operationLog.setUserName("#{currentUserName}"); OperationLogDetail annotation = signature.getMethod().getAnnotation(OperationLogDetail.class); if(annotation != null){ operationLog.setLevel(annotation.level()); operationLog.setDescribe(getDetail(((MethodSignature)joinPoint.getSignature()).getParameterNames(),joinPoint.getArgs(),annotation)); operationLog.setOperationType(annotation.operationType().getValue()); operationLog.setOperationUnit(annotation.operationUnit().getValue()); } //TODO 這裏保存日誌 System.out.println("記錄日誌:" + operationLog.toString()); // operationLogService.insert(operationLog); } /** * 對當前登陸用戶和佔位符處理 * @param argNames 方法參數名稱數組 * @param args 方法參數數組 * @param annotation 註解信息 * @return 返回處理後的描述 */ private String getDetail(String[] argNames, Object[] args, OperationLogDetail annotation){ Map<Object, Object> map = new HashMap<>(4); for(int i = 0;i < argNames.length;i++){ map.put(argNames[i],args[i]); } String detail = annotation.detail(); try { detail = "'" + "#{currentUserName}" + "'=》" + annotation.detail(); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object k = entry.getKey(); Object v = entry.getValue(); detail = detail.replace("{{" + k + "}}", JSON.toJSONString(v)); } }catch (Exception e){ e.printStackTrace(); } return detail; } @Before("operationLog()") public void doBeforeAdvice(JoinPoint joinPoint){ System.out.println("進入方法前執行....."); } /** * 處理完請求,返回內容 * @param ret */ @AfterReturning(returning = "ret", pointcut = "operationLog()") public void doAfterReturning(Object ret) { System.out.println("方法的返回值 : " + ret); } /** * 後置異常通知 */ @AfterThrowing("operationLog()") public void throwss(JoinPoint jp){ System.out.println("方法異常時執行....."); } /** * 後置最終通知,final加強,無論是拋出異常或者正常退出都會執行 */ @After("operationLog()") public void after(JoinPoint jp){ System.out.println("方法最後執行....."); } }
package com.wwj.springboot.annotation; import com.wwj.springboot.enums.OperationType; import com.wwj.springboot.enums.OperationUnit; import java.lang.annotation.*; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ //@OperationLogDetail(detail = "經過手機號[{{tel}}]獲取用戶名",level = 3,operationUnit = OperationUnit.USER,operationType = OperationType.SELECT) @Documented @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface OperationLogDetail { /** * 方法描述,可以使用佔位符獲取參數:{{tel}} */ String detail() default ""; /** * 日誌等級:本身定,此處分爲1-9 */ int level() default 0; /** * 操做類型(enum):主要是select,insert,update,delete */ OperationType operationType() default OperationType.UNKNOWN; /** * 被操做的對象(此處使用enum):能夠是任何對象,如表名(user),或者是工具(redis) */ OperationUnit operationUnit() default OperationUnit.UNKNOWN; }
package com.wwj.springboot.enums; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ public enum OperationType { /** * 操做類型 */ UNKNOWN("unknown"), DELETE("delete"), SELECT("select"), UPDATE("update"), INSERT("insert"); private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } OperationType(String s) { this.value = s; } }
package com.wwj.springboot.enums; /** * Created by IntelliJ IDEA * 被操做的單元 * @author weiwenjun * @date 2018/9/12 */ public enum OperationUnit { /** * 被操做的單元 */ UNKNOWN("unknown"), USER("user"), EMPLOYEE("employee"), Redis("redis"); private String value; OperationUnit(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package com.wwj.springboot.model; import java.util.Date; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ public class OperationLog { private String id; private Date createTime; /** * 日誌等級 */ private Integer level; /** * 被操做的對象 */ private String operationUnit; /** * 方法名 */ private String method; /** * 參數 */ private String args; /** * 操做人id */ private String userId; /** * 操做人 */ private String userName; /** * 日誌描述 */ private String describe; /** * 操做類型 */ private String operationType; /** * 方法運行時間 */ private Long runTime; /** * 方法返回值 */ private String returnValue; @Override public String toString() { return "OperationLog{" + "id='" + id + '\'' + ", createTime=" + createTime + ", level=" + level + ", operationUnit='" + operationUnit + '\'' + ", method='" + method + '\'' + ", args='" + args + '\'' + ", userId='" + userId + '\'' + ", userName='" + userName + '\'' + ", describe='" + describe + '\'' + ", operationType='" + operationType + '\'' + ", runTime=" + runTime + ", returnValue='" + returnValue + '\'' + '}'; } public Long getRunTime() { return runTime; } public void setRunTime(Long runTime) { this.runTime = runTime; } public String getReturnValue() { return returnValue; } public void setReturnValue(String returnValue) { this.returnValue = returnValue; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public String getOperationUnit() { return operationUnit; } public void setOperationUnit(String operationUnit) { this.operationUnit = operationUnit; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getArgs() { return args; } public void setArgs(String args) { this.args = args; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } public String getOperationType() { return operationType; } public void setOperationType(String operationType) { this.operationType = operationType; } }
package com.wwj.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ @SpringBootApplication public class AopApplication { public static void main(String[] args) { SpringApplication.run(AopApplication.class); } }
package com.wwj.springboot.controller; import com.wwj.springboot.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/12 */ @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; /** * 訪問路徑 http://localhost:11000/user/findUserNameByTel?tel=1234567 * @param tel 手機號 * @return userName */ @ResponseBody @RequestMapping("/findUserNameByTel") public String findUserNameByTel(@RequestParam("tel") String tel){ return userService.findUserName(tel); } }
package com.wwj.springboot.service; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/13 */ public interface UserService { /** * 獲取用戶信息 * @return * @param tel */ String findUserName(String tel); }
package com.wwj.springboot.service.impl; import com.wwj.springboot.annotation.OperationLogDetail; import com.wwj.springboot.enums.OperationType; import com.wwj.springboot.enums.OperationUnit; import com.wwj.springboot.service.UserService; import org.springframework.stereotype.Service; /** * Created by IntelliJ IDEA * * @author weiwenjun * @date 2018/9/13 */ @Service public class UserServiceImpl implements UserService { @OperationLogDetail(detail = "經過手機號[{{tel}}]獲取用戶名",level = 3,operationUnit = OperationUnit.USER,operationType = OperationType.SELECT) @Override public String findUserName(String tel) { System.out.println("tel:" + tel); return "zhangsan"; } }
本項目有兩個pom文件,父類的pom文件主要做用是對子類pom文件依賴的版本號進行統一管理。dom
1.最外層的pom文件配置以下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wwj.springboot</groupId> <artifactId>springboot</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>springboot-aop</module> </modules> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <properties> <fastjson.version>1.2.49</fastjson.version> </properties> <dependencyManagement> <dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.4.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> </dependencies> </dependencyManagement> </project>
2.子pom文件配置以下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>springboot</artifactId> <groupId>com.wwj.springboot</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>springboot-aop</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- spring-boot aop依賴配置引入 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> </dependencies> </project>
進入方法前執行..... tel:1234567 記錄日誌:OperationLog{id='cd4b5ba7-7580-4989-a75e-51703f0dfbfc', createTime=Fri Sep 14 08:54:55 CST 2018, level=3, operationUnit='user', method='com.wwj.springboot.service.impl.UserServiceImpl.findUserName', args='["1234567"]', userId='#{currentUserId}', userName='#{currentUserName}', describe=''#{currentUserName}'=》經過手機號["1234567"]獲取用戶名', operationType='select', runTime=4, returnValue='"zhangsan"'} 方法最後執行..... 方法的返回值 : zhangsan
感謝您的閱讀,若是您以爲閱讀本文對您有幫助,請點一下「推薦」按鈕。本文歡迎各位轉載,可是轉載文章以後必須在文章頁面中給出做者和原文鏈接。