功能简介
本文主要记录如何使用aop切面的方式来实现日志记录功能。
主要记录的信息有: 操作人,方法名,参数,运行时间,操作类型(增删改查),详细描述,返回值。
功能结构图

代码实现
这个是最主要的类,可以使用自定义注解或针对包名实现AOP增强。
1)这里实现了对自定义注解的环绕增强切点,对使用了自定义注解的方法进行AOP切面处理;
2)对方法运行时间进行监控;
3)对方法名,参数名,参数值,对日志描述的优化处理;
在方法上增加@Aspect 注解声明切面,使用@Pointcut 注解定义切点,标记方法。
使用切点增强的时机注解:@Before,@Around,@AfterReturning,@AfterThrowing,@After
package com.sumeng.aspect;
import com.alibaba.fastjson.JSON;
import com.sumeng.annotaction.Loganno;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
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;
import java.lang.reflect.Method;
/**
* @description:
* @author: chenzuolin
* @time: 2020/8/2 22:18
*/
@Component
@Aspect
public class Log {
private static final String LINE_SEPARATOR = System.lineSeparator();
Logger log = LoggerFactory.getLogger(Log.class);
@Pointcut("@annotation(com.sumeng.annotaction.Loganno)")
public void log(){};
@Before("log()")
public void before(JoinPoint joinPoint) throws Exception {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String methodDetailDescription = this.getAspectMethodLogDescJP(joinPoint);
log.info("------------------------------- start --------------------------");
/**
* 打印自定义方法描述
*/
log.info("Method detail Description: {}", methodDetailDescription);
/**
* 打印请求入参
*/
log.info("Request Args: {}", JSON.toJSONString(joinPoint.getArgs()));
/**
* 打印请求方式
*/
log.info("Request method: {}", request.getMethod());
/**
* 打印请求 url
*/
log.info("Request URL: {}", request.getRequestURL().toString());
/**
* 打印调用方法全路径以及执行方法
*/
log.info("Request Class and Method: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
}
@Around("log()")
public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
String aspectMethodLogDescPJ = this.getAspectMethodLogDescPJ(joinPoint);
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
/**
* 输出结果
*/
log.info("{},Response result : {}", aspectMethodLogDescPJ, JSON.toJSONString(result));
/**
* 方法执行耗时
*/
log.info("Time Consuming: {} ms", System.currentTimeMillis() - startTime);
return result;
}
public String getAspectMethodLogDescJP(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
return getAspectMethodLogDesc(targetName, methodName, arguments);
}
public String getAspectMethodLogDescPJ(ProceedingJoinPoint proceedingJoinPoint) throws Exception {
String targetName = proceedingJoinPoint.getTarget().getClass().getName();
String methodName = proceedingJoinPoint.getSignature().getName();
Object[] arguments = proceedingJoinPoint.getArgs();
return getAspectMethodLogDesc(targetName, methodName, arguments);
}
public String getAspectMethodLogDesc(String targetName, String methodName, Object[] arguments) throws Exception {
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
StringBuilder description = new StringBuilder("");
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] clazzs = method.getParameterTypes();
if (clazzs.length == arguments.length) {
description.append(method.getAnnotation(Loganno.class).description());
break;
}
}
}
return description.toString();
}
@After("log()")
public void doAfter(JoinPoint joinPoint) throws Throwable {
log.info("------------------------------- End --------------------------" + LINE_SEPARATOR);
}
}
自定义注解
package com.sumeng.annotaction;
import java.lang.annotation.*;
/**
* @description:
* @author: chenzuolin
* @time: 2020/8/2 22:12
*/
@Target(ElementType.METHOD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Loganno {
String description() default "";
}
controller
package com.sumeng.controller;
import com.sumeng.annotaction.Loganno;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description:
* @author: chenzuolin
* @time: 2020/8/2 22:11
*/
@RestController
public class HelloController {
@GetMapping("/hello")
@Loganno(description = "hello测试自定义注解")
public String hello(){
return "nihao";
}
}
打印结果

导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
本文介绍了一种使用AOP切面技术实现日志记录功能的方法,包括操作人、方法名、参数等信息的记录,并通过自定义注解增强代码的可读性和维护性。
2088

被折叠的 条评论
为什么被折叠?



