package cn.nuc.zp.aop;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Aspect
@Component
public class ApiLogAspect {
private static Logger logger = LoggerFactory.getLogger(ApiLogAspect.class);
private final ObjectMapper mapper;
@Autowired
public ApiLogAspect(ObjectMapper mapper) {
this.mapper = mapper;
}
@Pointcut("execution(* cn.nuc.zp.controller..*.*(..))")
public void apiLog() {
}
@Before("apiLog()")
public void before(JoinPoint joinPoint) {
for (Object object : joinPoint.getArgs()) {
if (object instanceof MultipartFile
|| object instanceof HttpServletRequest
|| object instanceof HttpServletResponse
) {
continue;
}
try {
if (logger.isDebugEnabled()) {
logger.debug(
joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()
+ " : request parameter : " + mapper.writeValueAsString(object)
);
}
} catch (Exception e) {
logger.error("{}", e.getMessage());
}
}
}
@Around("apiLog()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object response = proceedingJoinPoint.proceed();
if (logger.isDebugEnabled()) {
logger.debug("response parameter : " + mapper.writeValueAsString(response));
logger.debug("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
}
return response;
}
}
转载:https://blog.csdn.net/zpwangshisuifeng/article/details/100987046
查看评论