一.定义注解Log
pom.xml添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
配置文件
spring:
aop:
auto: true
proxy-target-class: true
1.用户在开启日志记录功能
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}
2.定义日志切面
@Aspect
@Component
public class LogsAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Pointcut("@annotation(com.example.springbootTest.common.annotation.Log)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point, time);
return result;
}
//处理日志,比如输出 保存到数据库...
void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String methodName = signature.getName();
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
logger.info("------------------------接口日志-----------------------"+"\n"+"类名称:"+className
+"\n"+"方法名:"+methodName+"\n"+"执行时间:"+time+"毫秒");
}
}
3.使用
@GetMapping("/test")
@Log
public String test(){
return "hello world";
}
结果:
2018-11-23 10:41:06 166128 [http-nio-8085-exec-2] INFO c.e.s.common.aop.LogAspect - ------------------------接口日志-----------------------
类名称:com.example.springbootTest.controller.TestController
方法名:test
执行时间:38毫秒
二.不用注解形式
在controller执行执行打印日志,示例代码:
@Component //声明组件
@Aspect // 声明切面
@ComponentScan //组件自动扫描
@EnableAspectJAutoProxy //spring自动切换JDK动态代理和CGLIB
public class LogAspect {
@Resource
HttpServletRequest request;
/**
*自定义日志
*/
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
/**
* 在方法执行前进行切面
*/
@Pointcut("execution(* com.example.springbootTest..*.*(..)) && (@annotation(org.springframework.web.bind.annotation.GetMapping)||@annotation(org.springframework.web.bind.annotation.PutMapping)||@annotation(org.springframework.web.bind.annotation.DeleteMapping)||@annotation(org.springframework.web.bind.annotation.PostMapping)||@annotation(org.springframework.web.bind.annotation.RequestMapping))")
public void log() {
}
@Before("log()")
public void before(JoinPoint point) {
logger.info("---------------------请求开始---------------------");
logger.info("请求地址:"+request.getRequestURL().toString());
logger.info("请求方式:"+request.getMethod());
logger.info("请求类方法:"+point.getSignature());
logger.info("请求类方法参数:"+ Arrays.toString(point.getArgs()));
logger.info("-------------------------------------------------");
}
}