网站下载免费的视频软件,wordpress中国化,河北邢台贴吧,腾讯企业邮箱登录入口网页版入口基于自定义注解与 AOP 切面实现接口日志全面数据库存储
一、引言
在当今复杂的软件系统开发与运维过程中#xff0c;详细且精准地记录接口的各项信息对于系统性能监测、问题排查、安全审计以及业务分析都有着极为关键的意义。本文将深入讲解如何运用自定义注解与 AOP#x…基于自定义注解与 AOP 切面实现接口日志全面数据库存储
一、引言
在当今复杂的软件系统开发与运维过程中详细且精准地记录接口的各项信息对于系统性能监测、问题排查、安全审计以及业务分析都有着极为关键的意义。本文将深入讲解如何运用自定义注解与 AOP面向切面编程技术全面地将接口的入参信息、出参信息以及接口执行用时记录到数据库中从而构建一套完善的接口日志管理体系。
二、技术选型与环境搭建
本项目基于 Java 语言开发采用 Spring Boot 框架搭建应用的基础架构这有助于快速整合各类组件并实现便捷的开发部署。在数据库层面选用 MySQL 作为数据存储的后端以其稳定性和广泛的应用支持来保障日志数据的可靠存储。数据持久化操作借助 MyBatis 框架实现它能够高效地处理 Java 对象与数据库表之间的映射关系。日志记录方面依旧以 SLF4J 作为抽象层结合 Logback 进行灵活的日志打印配置。
三、数据库设计优化
重新设计用于存储接口日志的数据库表以更好地适应记录入参、出参和执行用时的需求
CREATE TABLE interface_log (id INT AUTO_INCREMENT PRIMARY KEY,interface_path VARCHAR(255) NOT NULL,invocation_time TIMESTAMP NOT NULL,user_info VARCHAR(255),input_parameters VARCHAR(255),output_parameters VARCHAR(255),execution_time BIGINT,description VARCHAR(255)
);新增的 execution_time 字段用于存储接口执行所耗费的时间单位为毫秒以便后续对接口性能进行分析评估。
四、自定义注解设计
定义 LoggableFullDB 自定义注解用于明确需要进行全面日志记录到数据库的接口方法
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 LoggableFullDB {String value() default ;
}五、AOP 切面实现升级
构建更为完善的 AOP 切面类 LoggingAspectFullDB负责精确地拦截被 LoggableFullDB 注解标记的方法并全面地记录接口相关信息到数据库
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;Aspect
Component
public class LoggingAspectFullDB {private static final Logger logger LoggerFactory.getLogger(LoggingAspectFullDB.class);// 在方法执行前记录相关信息并准备插入数据库的数据Before(annotation(loggableFullDB))public void beforeMethodExecution(JoinPoint joinPoint, LoggableFullDB loggableFullDB) {ServletRequestAttributes attributes (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request attributes.getServletRequest();InterfaceLogDTO logDTO new InterfaceLogDTO();// 记录接口路径地址logDTO.setInterfacePath(request.getRequestURI());// 记录调用时间logDTO.setInvocationTime(new Date());// 尝试获取用户信息假设用户信息存储在请求头中的某个字段可根据实际情况修改logDTO.setUserInfo(request.getHeader(user));// 记录方法参数logDTO.setInputParameters(Arrays.toString(joinPoint.getArgs()));logDTO.setDescription(loggableFullDB.value());// 记录方法开始执行时间用于后续计算执行用时logDTO.setStartTime(System.currentTimeMillis());// 此处可将 logDTO 传递给数据库操作层进行插入操作的准备例如调用 service 层方法logService.prepareLogInsert(logDTO);}// 在方法执行成功返回后记录出参信息并完成数据库插入操作AfterReturning(pointcut annotation(loggableFullDB), returning result)public void afterMethodExecution(JoinPoint joinPoint, LoggableFullDB loggableFullDB, Object result) {InterfaceLogDTO logDTO logService.getLogDTOForUpdate(); // 获取之前准备的 logDTO// 记录返回结果logDTO.setOutputParameters(result.toString());// 计算接口执行用时并存储long endTime System.currentTimeMillis();logDTO.setExecutionTime(endTime - logDTO.getStartTime());// 执行数据库插入操作logService.insertLog(logDTO);}
}其中 InterfaceLogDTO 数据传输对象也相应地更新
public class InterfaceLogDTO {private String interfacePath;private Date invocationTime;private String userInfo;private String inputParameters;private String outputParameters;private Long executionTime;private Long startTime;private String description;// 省略 getter 和 setter 方法
}六、数据库操作层实现优化
优化 LogService 接口及其实现类 LogServiceImpl确保与新的日志记录需求和数据库表结构相适配
public interface LogService {void prepareLogInsert(InterfaceLogDTO logDTO);InterfaceLogDTO getLogDTOForUpdate();void insertLog(InterfaceLogDTO logDTO);
}import org.springframework.stereotype.Service;Service
public class LogServiceImpl implements LogService {private ThreadLocalInterfaceLogDTO logDTOLocal new ThreadLocal();Overridepublic void prepareLogInsert(InterfaceLogDTO logDTO) {logDTOLocal.set(logDTO);}Overridepublic InterfaceLogDTO getLogDTOForUpdate() {return logDTOLocal.get();}Overridepublic void insertLog(InterfaceLogDTO logDTO) {// 使用 MyBatis 或其他数据库操作工具将 logDTO 中的数据插入到数据库表中// 这里省略具体的数据库插入代码例如sqlSession.insert(insertInterfaceLog, logDTO);logDTOLocal.remove();}
}七、在接口中应用自定义注解
在具体的接口方法上应用 LoggableFullDB 注解如下示例
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;RestController
public class OrderController {LoggableFullDB(获取订单详情接口)GetMapping(/order/details)public Order getOrderDetails(String orderId) {// 模拟获取订单详情的业务逻辑Order order new Order();order.setId(orderId);order.setCustomerName(John Doe);order.setTotalAmount(100.0);return order;}
}八、日志打印配置
在 application.properties 或 application.yml 文件中配置 Logback 进行日志打印输出
# Logback 配置
logging:level:root: INFOpattern:console: %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n九、总结
通过精心设计的自定义注解、强大的 AOP 切面技术以及完善的数据库操作层构建我们成功实现了接口日志的全面数据库存储方案。该方案能够精确地记录接口的入参信息、出参信息以及执行用时并将这些关键数据可靠地存储到数据库中。这不仅为系统的运维监控提供了丰富且准确的数据依据也为后续的业务分析和性能优化奠定了坚实的基础。在实际项目应用中可依据具体业务场景和需求进一步对数据库表结构、日志记录策略以及数据处理流程进行深度优化与扩展以实现更为高效和智能的接口日志管理系统。