接口日志

This commit is contained in:
wangw 2025-02-14 18:19:58 +08:00
parent ff399970db
commit b10ba2616c
1 changed files with 75 additions and 0 deletions

View File

@ -0,0 +1,75 @@
package com.czg.config;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.czg.utils.ServletUtil;
import com.google.gson.Gson;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* 方法调用统一切面处理
*/
@Aspect
@Component
@Slf4j
//@Profile({"dev"})
public class ControllerAspect {
@Pointcut("execution(public * (com.czg.controller.*.controller..*).*(..)))")
public void pkg() {
}
@Around("pkg()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
//避免回填
Object[] args = pjp.getArgs();
// 如果请求参数中包含HttpServletRequest剔除HttpServletRequest
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest) {
args[i] = null;
}
}
String params = new Gson().toJson(args);
// 执行被拦截的方法
Object result = pjp.proceed();
long end = System.currentTimeMillis();
HttpServletRequest request = ServletUtil.getRequest();
String method = request.getMethod();
String requestUrl = request.getRequestURL().toString();
String requestIp = ServletUtil.getClientIPByHeader(request);
long useTime = end - start;
ThreadUtil.execAsync(() -> {
//请求的参数
String resultJson = JSONObject.toJSONString(result);
try {
if (StrUtil.isNotBlank(resultJson) && !"null" .equals(resultJson)) {
log.info("\n>>>>>> {} {}" +
"\n>>>>>> IP: {} " +
"\n>>>>>> execute time:{}ms " +
"\n>>>>>> Request: {}" +
"\n>>>>>> Response: {}",
method, requestUrl, requestIp, useTime,
params,
resultJson
);
}
} catch (Exception e) {
log.error("Request 为空" + e.getMessage());
}
});
return result;
}
}