SpringBoot全局日志管理(AOP)


1、在pom.xml中引入aop的jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2、創建WebLogAspect類

package com.cppdy.log;

import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; 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.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Aspect @Component public class WebLogAspect { @Pointcut("execution(public * com.cppdy.controller..*.*(..))") public void webLog() { } @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 System.out.println("URL:" + request.getRequestURL().toString()); System.out.println("HTTP_METHOD:" + request.getMethod()); System.out.println("IP:" + request.getRemoteAddr()); Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String name = enu.nextElement(); System.out.println("name:" + name + ",value:" + request.getParameter(name)); } } @AfterReturning(returning="ret",pointcut="webLog()") public void doAfterReturning(Object ret)throws Throwable { //處理完請求,返回內容 System.out.println("RESPONSE:"+ret); } }

3、訪問login方法測試全局日志管理功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM