参考springboot+log4j统一处理请求日志(AOP)
有关请求参数部分做了微调,以及使用了项目内的Slf4j记录日志。
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
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.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* @author heyang
*/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
@Pointcut("execution(public * com.hws.manager..controller.*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null){
return;
}
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("---------------request----------------");
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
Map<String,Object> map = new HashMap<>();
try {
Object[] params = joinPoint.getArgs();
for (int i = 0; i < params.length; i++) {
if (params[i] instanceof BindingResult
|| params[i] instanceof HttpRequest
|| params[i] instanceof HttpResponse){
continue;
}
map.put("param-" + i,params[i]);
}
}catch (Exception e){
}
log.info("PARAMS_JSON : " + map);
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
log.info("---------------response----------------");
// 处理完请求,返回内容
log.info("RESPONSE : " + ret);
}
}