要明确AOP的三个基本概念:
1.Advice(通知),定义在连接点需要做什么;
2.Pointcut(切点),决定了Advice通知作用于哪个连接点;
3.Advisor(通知器),定义应该使用哪个通知并在哪个关注点使用它。
下面的UserLogAspect就是一个通知器,其中的切点已经标注,通知为前通知(先于切点执行)和后通知(后于切点执行)。
@Aspect //切面注解
@Component
@Order(-5) //次序问题
public class UserLogAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(public * xxx.xxx.xxx.controllers.CustomerController.*(..))")
//目标函数内不需要做任何操作,因为这里已注明目标函数完整路径。
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint){
// 接收到请求,记录请求内容
logger.info("WebLogAspect.doBefore()");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
logger.info("Headers-Uuid : " + request.getHeader("Uuid"));
//获取所有参数方法一:
Enumeration<String> enu=request.getParameterNames();
while(enu.hasMoreElements()){
String paraName=(String)enu.nextElement();
System.out.println(paraName+": "+request.getParameter(paraName));
}
}
@After("webLog()")
public void doAfterReturning(JoinPoint joinPoint){
// 处理完请求,返回内容
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("WebLogAspect.doAfterReturning()");
}
}
日志路径的配置文件:log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="DEBUG"/>
<appender name="aspectAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--<file>D:/logs/bribery.log</file>-->
<!--这句如果不注释掉,则fileNamePattern中的设置将会无效-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>D:/logs/bribery-%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.baojinsuo.springboot.user_server.user_log_aspect.UserLogAspect" level="DEBUG" additivity="false">
<appender-ref ref="aspectAppender" />
</logger>
</configuration>
最后运行项目,日志就会自动存于指定目录: