通用AOP日志模板工具
package com.tbc.gkk.common;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用于记录日志的工具类,它里面提供了公共的代码
*/
@Slf4j
@Component
@Aspect
public class LoggerAop {
/**
* @author gkk
* @date 2019/6/13 0:04
* @param [p]
* @return void
* @describe 前置日志,用于打印进入方法的信息
* @version 1.0
*/
@Before("pt1()")
public void beforePrintLog(JoinPoint p) throws IOException {
startTime = System.currentTimeMillis();
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
HttpServletRequest request = sra.getRequest();
log.info(st,request.getRequestURL(),request.getRemoteAddr(),request.getMethod(),p.getSignature().getDeclaringTypeName(),p.getSignature().getName(),JSONObject.toJSONString(p.getArgs()));
}
@AfterReturning("pt1()")
public void afterReturningPrintLog() {
log.info("方法执行总时长:{}毫秒",(System.currentTimeMillis()-startTime));
}
/**
* @author gkk
* @date 2019/6/13 0:06
* @param [result]
* @return void
* @describe 用于打印返回值
* @version 1.0
*/
@AfterReturning(returning = "result", pointcut = "pt1()")
public void exAfterReturning(Object result) {
log.info("执行返回值:{}",JSONObject.toJSONString(result));
}
public static final String st = "url:{},ip:{},requestMethod:{}class:{},method:{},args:{}";
//开始进入方法的时间
private Long startTime = 0L;
/**
* 配置切入点:
* 1、execution(): 表达式主体。
*
* 2、第一个*号:表示返回类型,*号表示所有的类型。
*
* 3、包名:表示需要拦截的包名,后面的两个句点
*
* 4、 ..表示当前包和当前包的所有子包
*
* 5、第二个*号:表示类名,*号表示所有的类。
*
* 6、最后这个星号表示方法名,*号表示所有的方法,
*
* 7、后面括弧里面表示方法的参数 (..),两个句点表示任何参数。
*
*/
@Pointcut("execution(* com.tbc.gkk.contorller..*.*(..))")
private void pt1() {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.*"></context:component-scan>
<!-- 配置spring开启注解AOP的支持,使用注解写aop必须要开启 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
总结:
1.配置切面类
2.开启注解支持
3.切入点的类必须注入到spring 容器中!