您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關使用java注解和aspectj AOP怎么實現打印日志,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
1.首先需要自定義注解:
systemName:表示該系統的名稱。
bizCode:表示具體的方法描述
logtype:表示日志的格式類型
package myspring; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface LogAnnotation { String systemName(); String bizCode(); LogType logtype() default LogType.TIME; }
package myspring; public enum LogType { TIME("TIME", "方法調用時間"), PARAM("PARAM", "參數打印"); private String type; private String desc; LogType(String type, String desc) { this.type = type; this.desc = desc; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
其中execution(* *(..))
第一個* :表示所有返回值
第二個* :表示所有包匹配規則和所有類匹配規則以及所有方法匹配規則
兩個點.. :表示任何參數匹配
例如:
execution(* *..*Service.*(..))
表示任何返回值 任何包以Service結尾的類或者實現類的任何方法任何參數
*.. :表示所有包
* :Service表示所有以Service結尾的類或者實現類
execution(* cn.lijie.MyService.*(..))
表示任何返回值 cn.lijie包下面 MyService類或者實現類的所有方法 所有參數
代碼如下:
package myspring; import com.alibaba.fastjson.JSON; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.util.StopWatch; import org.springframework.util.StringUtils; @Component @Aspect public class LogAspect { private static Logger thisLog = LoggerFactory.getLogger(LogAspect.class); private static Logger timeLog = LoggerFactory.getLogger(TimeTypeLog.class); private static Logger paramLog = LoggerFactory.getLogger(ParamTypeLog.class); @Around("execution(* *(..)) && @annotation(logAnnotation)") public Object log(ProceedingJoinPoint point, LogAnnotation logAnnotation) { StopWatch stop = new StopWatch(); stop.start(); boolean flag = false; Object retValue = null; try { retValue = point.proceed(); flag = true; } catch (Throwable throwable) { throwable.printStackTrace(); } finally { stop.stop(); if (logAnnotation.logtype().equals(LogType.TIME)) { timeLog(this.getMethod(point), point, stop.getTotalTimeMillis(), logAnnotation, flag); } else { paramLog(this.getMethod(point), point, retValue); } } return retValue; } private void timeLog(String method, ProceedingJoinPoint point, long totalTimeMillis, LogAnnotation logAnnotation, boolean flag) { timeLog.info("系統為:{},調用的方法名字:{},調用是否成功:{},運行時間為:{}ms", logAnnotation.systemName(), method, flag, totalTimeMillis); } private void paramLog(String method, ProceedingJoinPoint point, Object retValue) { try { String result = JSON.toJSONString(retValue); //獲取入參 Object[] args = point.getArgs(); StringBuffer sb = new StringBuffer(); for (Object obj : args) { String str = JSON.toJSONString(obj); sb.append(subStr(str, 200)).append(" "); } paramLog.info("調用方法為:{},入參為:{},出參為:{}", method, sb, subStr(result, 200)); } catch (Exception e) { thisLog.warn("切面日志 參數日志打印異常,異常信息:{}", e.getMessage()); } } private String getMethod(ProceedingJoinPoint pjp) { MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); return methodSignature.getDeclaringTypeName() + "#" + methodSignature.getMethod().getName(); } private String subStr(String string, int length) { if (!StringUtils.isEmpty(string)) { if (string.length() > length) { string = string.substring(0, 200); return string; } } return string; } }
package myspring; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component("logTest") public class LogTest { private static Logger logger = LoggerFactory.getLogger(LogTest.class); @LogAnnotation(systemName = "計算器系統", bizCode = "+", logtype = LogType.TIME) public int testLog01(int a, int b) { logger.info("進入+運算"); return a + b; } @LogAnnotation(systemName = "計算器系統", bizCode = "-", logtype = LogType.PARAM) public int testLog02(int a, int b) { logger.info("進入-運算"); return a - b; } }
package myspring; public class TimeTypeLog {
package myspring; public class ParamTypeLog { }
<context:component-scan base-package="myspring"/> <aop:aspectj-autoproxy/>
package myspring; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); LogTest logTest = (LogTest) context.getBean("logTest"); logTest.testLog01(1, 2); logTest.testLog02(3, 4); context.registerShutdownHook(); } }
<properties> <spring_version>4.3.8.RELEASE</spring_version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.11</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.11</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency> </dependencies>
最后執行測試的類,日志打印如下:
補充:spring boot 自定義注解實現自動打印方法日志(入參和返回值)
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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.aline</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.7</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
SysLog.java
package com.aline.demo.annotation; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SysLog { }
LoggerCache.class package com.aline.demo.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; public class LoggerCache { /** * 日志實例記錄在內存中 */ private static HashMap<String, Logger> LOGERS = new HashMap<String, Logger>(); /** * 根據類名獲取緩存的日志實例 * @param className 包名加類名 this.getClass().getName(); * @return */ public static Logger getLoggerByClassName(String className) { // 從靜態map中獲取日志實例 Logger logger = LOGERS.get(className); // 如果沒取到 if (logger == null) { // 創建一個日志實例 logger = LoggerFactory.getLogger(className); // 加入到靜態map中 LOGERS.put(className, logger); } // 返回 return logger; } }
SysLogAspect.java
package com.aline.demo.aspect; import com.alibaba.fastjson.JSON; import com.aline.demo.util.LoggerCache; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Aspect @Component public class SysLogAspect { @Pointcut("@annotation(com.aline.demo.annotation.SysLog)") public void log() { } /** * 加入注解自動記錄方法日志 * * @param joinPoint * @return * @throws Throwable */ @Around(value = "log()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { // 獲取執行方法的類的名稱(包名加類名) String className = joinPoint.getTarget().getClass().getName(); // 獲取實例和方法 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); // 從緩存中獲取日志實例 Logger log = LoggerCache.getLoggerByClassName(className); // 記錄日志 log.info(className + "." + method.getName() + "() 執行"); Object[] args = joinPoint.getArgs(); log.info("Params\t===》\t" + JSON.toJSONString(args)); // 執行方法獲取返回值 Object proceed = joinPoint.proceed(); // 記錄日志 log.info("Returns\t===》\t" + JSON.toJSONString(proceed)); // 返回 return proceed; } }
TestController.java
package com.aline.demo.controller; import com.aline.demo.annotation.SysLog; import com.aline.demo.util.LoggerCache; import org.slf4j.Logger; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; @RestController @RequestMapping("/test") public class TestController { static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); @GetMapping("/now") public String now(){ // 從緩存中獲取日志 Logger LOG = LoggerCache.getLoggerByClassName(this.getClass().getName()); LOG.info("自定義日志 ==》 日志內容。。。"); return sdf.format(new Date()); } @GetMapping("/hello") @SysLog() public String hello(String name){ return "Hello, " + name; } }
訪問 http://localhost:8080/test/hello?name=aline
打印日志:
2019-05-09 16:58:20.410 INFO 40004 --- [nio-8080-exec-1] c.aline.demo.controller.TestController : com.aline.demo.controller.TestController.hello() 執行,參數 ==》 2019-05-09 16:58:20.584 INFO 40004 --- [nio-8080-exec-1] c.aline.demo.controller.TestController : Params ===》 ["aline"] 2019-05-09 16:58:20.598 INFO 40004 --- [nio-8080-exec-1] c.aline.demo.controller.TestController : Returns ===》 "Hello, aline"
訪問 http://localhost:8080/now
打印日志:
2019-05-09 16:58:29.208 INFO 40004 --- [nio-8080-exec-3] c.aline.demo.controller.TestController : 自定義日志 ==》 日志內容。。。
以上就是使用java注解和aspectj AOP怎么實現打印日志,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。