首页 > 经验记录 > SpringBoot使用AOP配置Log4j日志切面

SpringBoot使用AOP配置Log4j日志切面

首先、最主要的,配置文件:application.yml和pom.xml得加上这几条配置

#定义日志文件路径
logging:
  file: logs/all.log
<!--aop-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

 
 
具体配置的切面类:

package top.yibobo.hospital.controller;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
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.util.Arrays;
@Aspect
@Component
@Order(3)//Order用来定义切面执行顺序
public class WebLogAspect {
    //定义日志记录器
    Logger logger = LoggerFactory.getLogger(this.getClass());
    ThreadLocal<Long> startTime = new ThreadLocal<>();//线程备份类,用来记录时间
    @Pointcut("execution(public  * top.yibobo.hospital.controller.*.*(..))")
    public void weblog(){}
    @Before("weblog()")
    public void dobefore(JoinPoint joinPoint){
        logger.info("前置通知:");
        //方法执行前的系统当前时间
        startTime.set(System.currentTimeMillis());
        //由于切面类不能从方法入参注入、所以只能这样获取servlet请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //让日志记录请求相关信息
        logger.info("URL:"+request.getRequestURL().toString());
        logger.info("METHOD:"+request.getMethod());
        logger.info("CLASS_METHOD:"+joinPoint.getSignature().getDeclaringTypeName()
                +"."+joinPoint.getSignature().getName());
        logger.info("ARGS:"+ Arrays.toString(joinPoint.getArgs()));
    }
    @AfterReturning(returning = "ret",pointcut = "weblog()")//返回值注入给ret
    public void doafter(Object ret){
        logger.info("后置通知:");
        logger.info("RESPONSE:"+ret);
        logger.info("SPEND:"+(System.currentTimeMillis()-startTime.get())+"MS");
    }
}

 

           


EA PLAYER &

历史记录 [ 注意:部分数据仅限于当前浏览器 ]清空

      00:00/00:00