统一controller的日志记录
定义切面,然后匹配controller,around进行log打印
@Slf4j
@Component
@Aspect
public class ControllerLogAspect {
@Pointcut("execution(* delta.main.controller..*(..))")
public void requestServer() {
}
@SneakyThrows
@Around("requestServer()")
public Object doAround(ProceedingJoinPoint pjp) {
//记录请求开始执行时间:
long beginTime = System.currentTimeMillis();
//获取请求信息
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
//获取请求地址、请求类名、方法名
String requestMethod = request.getMethod();
String requestURI = request.getRequestURI();
String methodName = pjp.getSignature().getName();
String clazzName = pjp.getTarget().getClass().getName();
//获取请求参数:
MethodSignature ms = (MethodSignature) pjp.getSignature();
//获取请求参数类型
String[] parameterNames = ms.getParameterNames();
//获取请求参数值
Object[] parameterValues = pjp.getArgs();
StringBuilder paramsStringBuilder = new StringBuilder();
//组合请求参数,进行日志打印
if (parameterNames != null && parameterNames.length > 0) {
for (int i = 0; i < parameterNames.length; i++) {
if ((parameterValues[i] instanceof HttpServletRequest) || (parameterValues[i] instanceof HttpServletResponse)) {
paramsStringBuilder.append("[").append(parameterNames[i]).append("=").append(parameterValues[i]).append("]");
} else {
paramsStringBuilder.append("[").append(parameterNames[i]).append("=").append(JsonUtils.toJSONString(parameterValues[i])).append("]");
}
}
}
Object result = pjp.proceed();
String resultJson = (result != null) ? ((result instanceof Result) ? JsonUtils.toJSONString(result) : String.valueOf(result)) : "";
//记录请求完成执行时间:
long usedTime = System.currentTimeMillis() - beginTime;
//记录日志
log.info("\n请求执行完毕!\n" +
"URI信息:{}\n" +
"请求方式:{}\n" +
"请求耗时:{}ms\n" +
"请求响应方法:{}\n" +
"请求参数列表:{}\n" +
"返回值:{}", requestURI, requestMethod,usedTime, clazzName + "#" + methodName, paramsStringBuilder.toString(), resultJson);
return result;
}
}
原创:做时间的朋友