背景
对出入站的请求进行统一的日志打印以及存储。
入站请求(应用于controller以及webservice)
使用aspect切面,只要使用@annotation(com.zg.common.annotation.Log)标注的方法都会进入此切面。
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* 处理入站请求的切面
*/
@Slf4j
@Aspect
@Component
public class RequestLogAspect {
@Resource
IRequestInfoService requestInfoService;
@Resource
private TaskExecutor logExecutor;
private final String SYSTEM = "";
/**
* execution 指定controller
* !execution 剔除指定controller下的方法
*/
@Pointcut("@annotation(com.zg.common.annotation.Log)")
public void requestLogAspect() {
}
@Around("requestLogAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 获得注解
Log ctrlLog = getAnnotationLog(joinPoint);
ApiOperation apiOperation = getAnnotationApiOperation(joinPoint);
Object ret = null;
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
Map<String, String> paramMap = new HashMap<>();
String methodName = null;
String remoteIP = null;
LocalDateTime startTime = LocalDateTime.now(ZoneId.systemDefault());
String exceptionMessage = null;
Map<String, String> selectedHeaderMap = new HashMap<>();
try {
// 接收到请求,记录请求内容
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 记录下请求内容
log.info("请求类型 : {} ,请求URL : {}", request.getMethod(), request.getRequestURL());
remoteIP = request.getRemoteAddr();
log.info("请求IP : {}", remoteIP);
methodName