利用Spring AOP统一处理打印请求日志
1、定义切点:
@Pointcut(value = "execution(public * com.longc..*.controller..*.*(..))")
切点配置说明可参考:https://www.cnblogs.com/zhangxufeng/p/9160869.html 写的比较全
2、处理逻辑:
示例:
@Component
@Aspect
@Order(-1)
@Slf4j
public class LogParamAspect {
@Pointcut(value = "execution(public * com.longc..*.controller..*.*(..))")
public void webLog() {
}
@Before(value = "webLog()")
public void doBefore(JoinPoint joinPoint) {
try {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
String url = request.getRequestURL().toString();
String classMethod = joinPoint.getSignature().getDeclaringType().getSimpleName() + "." + joinPoint.getSignature().getName();
Signature signature = joinPoint.getSignature();
StringBuilder sb = new StringBuilder();
sb.append("URL -> ").append(url).append(" | ").append("CLASS_METHOD -> ").append(classMethod);
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.getAnnotation(NotLogHeader.class) == null) {
String headers = buildRequestHeaders(request);
if (!StringUtil.isTrimBlank(headers)) {
sb.append(" | ").append("HEADER -> ").append(headers);
}
}
if (method.getAnnotation(NotLogParam.class) == null) {
String params = buildRequestParams(request);
if (!StringUtil.isTrimBlank(params)) {
sb.append(" | ").append("PARAMS -> ").append(params);
}
}
log.info(sb.toString());
} catch (Throwable ex) {
log.error("HaLogParamAspect error.", ex);
}
}
/**
* 组装请求头信息(只打印配置需要打印的)
*
* @see com.longc.core.constant.CommonRequestHeader NEED_LOG_HEADER_LIST
*/
private String buildRequestHeaders(HttpServletRequest request) {
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames == null) {
return "";
} else {
StringBuilder sb = new StringBuilder();
while (headerNames.hasMoreElements()) {
String nextElement = headerNames.nextElement();
if (!NEED_LOG_HEADER_LIST.contains(nextElement)) {
continue;
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(nextElement).append("=").append(request.getHeader(nextElement));
}
return sb.toString();
}
}
/**
* 组装请求参数信息
*/
private String buildRequestParams(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
if (MapUtil.isBlank(parameterMap)) {
return "";
} else {
StringBuilder sb = new StringBuilder();
for (String key : parameterMap.keySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key).append("=").append(ArrayUtil.toString(parameterMap.get(key)));
}
return sb.toString();
}
}
}