SpringBoot使⽤AspectJ为controller层添加⽇志功能 应⽤类编写:
package com.zhong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import t.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy // 相当xml配置 <aop:aspectj-autoproxy/>
public class SpringbootFescarDemoApplication implements TransactionManagementConfigurer {
public static void main(String[] args) {
//SpringApplication.setAddCommandLineProperties(false);
SpringApplication.run(SpringbootFescarDemoApplication.class, args);
}
}
切⾯类编写:
package com.zhong.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import annotation.Order;
import org.springframework.stereotype.Component;
import org.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
/**
* Web层⽇志切⾯
*/
@Aspect
@Order(5)
@Component
public class WebLogAspect {
private Logger logger = Logger(getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>();
/**
* A join point is in the web layer if the method is defined
* in a type in someapp.web package or any sub-package
* under that.
*/
@Pointcut("within(com.zhong.web..*)")
public void webLog(){}
springboot aop
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestAttributes();
HttpServletRequest request = Request();
// 记录下请求内容
logger.info("URL : " + RequestURL().toString());
logger.info("HTTP_METHOD : " + Method());
logger.info("IP : " + RemoteAddr());
logger.info("CLASS_METHOD : " + Signature().getDeclaringTypeName() + "." + Signature().getName()); logger.info("ARGS : " + Args()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - ()));
}
}
控制台输出:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论