完整代码https://gitee.com/zcjlq/demo_aop_log
定义注解类
package com.example.annotation;
import com.example.enums.BusinessTypeEnum;
import java.lang.annotation.*;
@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 日志标题
*/
String title() default "";
/**
* 操作类型
*/
BusinessTypeEnum businessType() default BusinessTypeEnum.OTHER;
}
切面拦截(核心)
package com.example.config;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.example.annotation.Log;
import com.example.model.SysLog;
import com.example.service.ISysLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;
@Aspect
@Component
public class LogConfig {
private static final Logger log = LoggerFactory.getLogger(LogConfig.class);
/**
* 引入日志Service,用于存储数据进数据库
*/
@Autowired
private ISysLogService sysLogService;
/**
* 配置切入点-xxx代表自定义注解的存放位置
*/
@Pointcut("@annotation(com.example.annotation.Log)")
public void logPointCut() {
}
/**
* 处理完请求后执行此处代码
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
handleLog(joinPoint, controllerLog, null, jsonResult);
}
/**
* 如果处理请求时出现异常,在抛出异常后执行此处代码
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
handleLog(joinPoint, controllerLog, e, null);
}
/**
* 日志处理
*/
protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
try {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
// 获取当前的用户
String userName = "genius";
// *========数据库日志=========*//
SysLog sysLog = new SysLog();
sysLog.setStatus(1);
// 请求的地址 ip和localtion是前端获取到传过来的
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert requestAttributes != null;
HttpServletRequest request = requestAttributes.getRequest();
Map<String, String[]> parameterMap = request.getParameterMap();
String ip = getIpAddr(request);
sysLog.setOperIp(ip);
sysLog.setOperLocation(request.getHeader("location"));
sysLog.setOperParam(JSONUtil.toJsonStr(parameterMap));
sysLog.setOperUrl(request.getRequestURI());
sysLog.setOperName(userName);
if (e != null) {
sysLog.setStatus(0);
int length = e.getMessage().length();
sysLog.setErrorMsg(e.getMessage().substring(0, length > 2000 ? 2000 : length));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
sysLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
sysLog.setRequestMethod(request.getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, sysLog, jsonResult, request);
// 保存数据库
sysLog.setOperTime(LocalDateTime.now());
// 返回数据
sysLog.setJsonResult(jsonResult == null ? "" : jsonResult.toString());
// 将处理好的日至对象存储进数据库
sysLogService.save(sysLog);
} catch (Exception exp) {
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取操作ip地址
*
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 获取注解信息
*
* @param joinPoint
* @param log
* @param sysLog
* @param jsonResult
* @param request
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysLog sysLog, Object jsonResult, HttpServletRequest request) throws Exception {
// 设置action动作
sysLog.setBusinessType(log.businessType().ordinal());
sysLog.setTitle(log.title());
}
private void setRequestValue(JoinPoint joinPoint, SysLog sysLog, HttpServletRequest request) throws Exception {
String requestMethod = sysLog.getRequestMethod();
if (RequestMethod.PUT.name().equals(requestMethod) || RequestMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
sysLog.setOperParam(params.substring(0, 2000));
} else {
Map<?, ?> paramsMap = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
sysLog.setOperParam(paramsMap.toString().substring(0, 2000));
}
}
/**
* 解析方法参数信息
*
* @param paramsArray
* @return
*/
private String argsArrayToString(Object[] paramsArray) {
StringBuilder params = new StringBuilder();
if (paramsArray != null && paramsArray.length > 0) {
for (Object o : paramsArray) {
if (o != null && !isFilterObject(o)) {
try {
Object jsonObj = JSONUtils.toJSONString(o);
params.append(jsonObj.toString()).append(" ");
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
return params.toString().trim();
}
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Object value : collection) {
return value instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Object value : map.entrySet()) {
Map.Entry entry = (Map.Entry) value;
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
|| o instanceof BindingResult;
}
}
controller使用注解
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
private ISysLogService sysLogService;
@Log(title = "查询列表",businessType = BusinessTypeEnum.OTHER)
@GetMapping("list1")
public String list(@RequestParam("id") String id) {
return JSONUtil.toJsonStr(sysLogService.list());
}
}
完整代码:https://gitee.com/zcjlq/demo_aop_log
测试(使用idea Tools-Http Client)