SpringBoot中使用AOP切面機制,統一處理日誌
阿新 • • 發佈:2020-07-20
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 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.Enumeration;
@Aspect
@Component
public class WebLogConfig {
//獲取日誌資訊類
private static final Logger logger = LoggerFactory.getLogger(WebLogConfig.class);
@Pointcut("execution(* com.abc.controller.*.*(..))")
public void weblog(){}
@Before(value = "weblog()")
public void doBefore(JoinPoint joinPoint){
//獲取請求request
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
//通過servletRequestAttributes獲取request
HttpServletRequest request = attributes.getRequest();
//獲取請求的相應引數
StringBuffer url = request.getRequestURL();
//寫入請求的url
logger.info("URL: " + url.toString());
String method = request.getMethod();
//寫入請求的方法
logger.info("REQUEST_METHOD: " + method);
Enumeration<String> params = request.getParameterNames();
//遍歷請求引數
while(params.hasMoreElements()){
String name = params.nextElement();
logger.info("name{},params{}: " + name,request.getParameter(name));
}
//獲取請求的ip地址
String ip = request.getRemoteAddr();
//寫入請求的ip地址
logger.info("IP: " + ip);
}
@AfterReturning(pointcut = "weblog()",returning = "ret")
public void afterRet(Object ret){
//處理完請求響應內容
logger.info("RESPONSE: " + ret);
}
}