springboot通过自定义注解@Log实现日志打印
效果图
实操步骤
注意,本代码在springboot环境下运行,jdk1.8
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd</artifactId>
<version>3.3.7</version>
</dependency>
2.自定义日志注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日志注解
* @author woniu
*/
@Retention(RetentionPolicy.RUNTIME) //注解在源码、字节码、运行期间都存在
@Target({
ElementType.METHOD}) //作用在方法上
public @interface WoniuLog {
}
3.编写日志切面类
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
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;
import java.util.Optional;
import static jodd.util.MimeTypes.MIME_APPLICATION_JSON;
/**
* 日志切面类
* @author woniu
*/
@Aspect //代表这是一个切面类
@Component //注入到spring ioc
public class WoniuLogAspect {
private static final Logger log = LoggerFactory.getLogger(WoniuLogAspect.class);
public WoniuLogAspect() {
}
/**
* 前置通知:
* @annotation(WoniuLog) 表示切面只对加了@WoniuLog的方法生效
*/
@Before("@annotation(WoniuLog)")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = requestAttributes.getRequest();
String contentType = request.getContentType();
//只有contentType=application/json 的才加日志打印
if (StringUtils.isNotEmpty(contentType)&&contentType.contains(MIME_APPLICATION_JSON)) {
Class<?> clazz = joinPoint.getTarget().getClass();
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
log.info("------------------------------------------AOP日志start--------------------------------------------------------");
log.info("[AOP日志]:类名:{}", clazz.getName());
log.info("[AOP日志]:方法名:{}", method.getName());
Optional.ofNullable(joinPoint.getArgs()).ifPresent(x -> {
for (Object arg : x) {
String temp = JSONArray.toJSONString(x);
log.info("[AOP日志]:方法入参:{}", temp);
}
});
log.info("------------------------------------------AOP日志end--------------------------------------------------------");
}
}
}
}
4.UserController
@ApiOperation(value = "查询分页列表")
@PostMapping("/pageList")
@WoniuLog
public Result<PageResult<UserRespVo>> pageList(@RequestBody UserReqVo reqVo) {
PageResult<UserRespVo> result = userService.findList(reqVo);
return Result.ok(result);
}