爲何要經過AOP來統一處理日誌,由於隨着你項目的增大,方法增多,代碼量上來的時候,好比你有幾千個方法,你要打印日誌,你要在幾千個方法上面都加上冗餘的代碼logger.info(),讓你的代碼量瞬間提示幾千行,相信不少人都不想這樣去作,那麼接下來說一個統一的處理方法:web
springboot--使用AOP統一處理web請求日誌,首先來添加下pom文件依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<dependency>spring
而後貼下代碼:springboot
@Aspectbr/>@Component
public class WebLogAspect {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);ide
@Pointcut("execution(public * com.itmayiedu.controller.*.*(..))") public void webLog() { }
//經過使用AOP的前置通知來攔截請求信息
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到請求,記錄請求內容
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());spring-boot
Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String name = (String) enu.nextElement(); logger.info("name:{},value:{}", name, request.getParameter(name)); } } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 logger.info("RESPONSE : " + ret); }
}日誌