<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Slf4j
@Aspect
@Component
public class WebLogAspect {
@Pointcut("execution(public * com.test.controller..*.*(..))")
public void webLog() {
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) {
long beginTime = System.currentTimeMillis();
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String servletPath = null;
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
servletPath = request.getServletPath();
log.info("ip:{},path:{},param:{}", request.getRemoteAddr(), request.getServletPath(), getParams(proceedingJoinPoint.getArgs()));
}
Object result = null;
try {
result = proceedingJoinPoint.proceed();
log.info("{} end,cost:{}ms", servletPath, System.currentTimeMillis() - beginTime);
} catch (Throwable e) {
log.error("exception: ", e);
}
return result;
}
private Object getParams(Object[] args) {
JSONArray params = new JSONArray();
for (Object arg : args) {
if (arg instanceof Map<?, ?>) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) arg;
params.add(map);
} else if (arg instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) arg;
Map<String, String[]> paramMap = request.getParameterMap();
if (paramMap != null && paramMap.size() > 0) {
params.add(paramMap);
}
} else if (arg instanceof HttpServletResponse) {
} else {
params.add(BeanUtil.beanToMap(arg));
}
}
return params;
}
}