springBoot通过AOP(面向切面编程)实现自动保存请求日志
1.定义注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) // 指定该注解只能应用于方法上 @Retention(RetentionPolicy.RUNTIME) // 运行时生效 public @interface Loggable { }
2.编写切面的实现
import com.alibaba.fastjson.JSON; import com.jeecg.modules.jmreport.domain.SignUpInfo; import com.jeecg.modules.jmreport.mapper.WangXiaoMapper; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.Map; @Component @Aspect public class RequestResponseLoggerAspect { // private final Logger logger = LoggerFactory.getLogger(RequestResponseLoggerAspect.class); @Autowired private HttpServletRequest request; @Autowired private WangXiaoMapper wangXiaoMapper; @Around("@annotation(loggable)") public Object logMethodExecutionTime(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable { long startTime = System.currentTimeMillis(); String methodName = null; String className = null; Object result = null; Map<String, String[]> parameterMap = null; try { parameterMap = request.getParameterMap(); methodName = joinPoint.getSignature().getName(); className = joinPoint.getTarget().getClass().getSimpleName(); result = joinPoint.proceed(); //请求正常结束的日志 saveToDatabase(methodName, className, parameterMap, result); return result; } catch (Exception e){ //请求出错结束的日志 saveToDatabase(methodName, className, parameterMap,e.getMessage()); return e.getMessage(); } finally { // long endTime = System.currentTimeMillis(); // long executionTime = endTime - startTime; // logger.info("{}#{} executed in {} ms", className, methodName, executionTime); } } private void saveToDatabase(String methodName, String className, Map<String, String[]> parameterMap, Object result) { // 保存日志到数据库(写自己的业务代码,需要如何保存日志) } }
3.Application启动类上添加@EnableAspectJAutoProxy注解
4.需要保存日志的controller方法上添加注解@Loggable
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)