当前位置: 首页 > news >正文

记录用户业务请求日志

在用户的一般使用的时候,对于很多操作类型的接口,为了后面便于追查问题,需要记录用户的请求日志。

用户的请求日志目前主流的存储方式有:

  1. 日志文件
  2. 数据库
  3. MongoDB
  4. ElasticSearch

在商城的项目中暂时存放在MySQL中了。

增加注解

增加专门的注解标识哪些是需要记录用户日志的。

注解就叫BizLog注解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BizLog {String value() default "";
}

其中的value参数,用来接收用户自定义的日志描述。

后面只要有接口打上了这个注解,就会自动将用户的业务请求日志记录到数据库中。

增加业务日志表

为了方便后续追溯用户的请求行为,将用户的业务请求日志记录到数据库的某一张表中。

这样以后就可以通过这张表查询数据了。

CREATE TABLE `biz_log` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'ID',`method_name` varchar(30) NOT NULL COMMENT '方法名称',`description` varchar(30) NOT NULL COMMENT '描述',`request_ip` varchar(15) NOT NULL COMMENT '请求ip',`browser` varchar(200)  NULL COMMENT '浏览器',`url` varchar(100) NOT NULL COMMENT '请求地址',`param` varchar(300)  NULL COMMENT '请求参数',`time` int NOT NULL COMMENT '耗时,毫秒级',`exception` varchar(300)  NULL COMMENT '异常',`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '状态 1:成功 0:失败',`create_user_id` bigint NOT NULL COMMENT '创建人ID',`create_user_name` varchar(30) NOT NULL COMMENT '创建人名称',`create_time` datetime(3) DEFAULT NULL COMMENT '创建日期',`update_user_id` bigint DEFAULT NULL COMMENT '修改人ID',`update_user_name` varchar(30)  DEFAULT NULL COMMENT '修改人名称',`update_time` datetime(3) DEFAULT NULL COMMENT '修改时间',`is_del` tinyint(1) DEFAULT '0' COMMENT '是否删除 1:已删除 0:未删除',PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='业务日志表';

增加业务日志拦截器

package com.kailong.interceptor;import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.kailong.annotation.BizLog;
import com.kailong.entity.log.BizLogEntity;
import com.kailong.service.log.BizLogService;
import com.kailong.util.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Method;@Aspect
@Component
public class BizLogAspect {@Autowiredprivate BizLogService bizLogService;@Pointcut("@annotation(com.kailong.annotation.BizLog)")public void pointcut() {}@Around("pointcut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {long startTime = System.currentTimeMillis();HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();Object result = joinPoint.proceed();long time = System.currentTimeMillis() - startTime;BizLogEntity bizLogEntity = createBizLogEntity(joinPoint, httpServletRequest);bizLogEntity.setTime((int) time);bizLogEntity.setStatus(1);bizLogService.save(bizLogEntity);return result;}private String getParam(JoinPoint joinPoint) {StringBuilder params = new StringBuilder("{");Object[] argValues = joinPoint.getArgs();String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();if (argValues != null) {for (int i = 0; i < argValues.length; i++) {params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);}}return params.append("}").toString();}private BizLogEntity createBizLogEntity(JoinPoint joinPoint, HttpServletRequest httpServletRequest) {MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();BizLog bizLog = method.getAnnotation(BizLog.class);String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName();BizLogEntity bizLogEntity = new BizLogEntity();bizLogEntity.setDescription(bizLog.value());bizLogEntity.setMethodName(methodName);bizLogEntity.setStatus(1);bizLogEntity.setRequestIp(IpUtil.getIpAddr(httpServletRequest));bizLogEntity.setUrl(httpServletRequest.getRequestURI());bizLogEntity.setBrowser(getBrowserName(httpServletRequest));bizLogEntity.setParam(getParam(joinPoint));return bizLogEntity;}@AfterThrowing(pointcut = "pointcut()", throwing = "e")public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();BizLogEntity bizLogEntity = createBizLogEntity(joinPoint, httpServletRequest);bizLogEntity.setStatus(0);bizLogEntity.setException(e.getMessage());bizLogService.save(bizLogEntity);}private String getBrowserName(HttpServletRequest httpServletRequest) {String userAgentString = httpServletRequest.getHeader("User-Agent");UserAgent ua = UserAgentUtil.parse(userAgentString);return ua.getBrowser().toString();}
}

这个拦截器会记录用户业务请求的ip、地址、参数、浏览器和接口耗时都数据。

如果用户业务请求失败了,也会记录一条失败的数据。

BizLog相关类

(基础设置,实际项目需修改)

BizLogEntity

package com.kailong.entity.log;/*** created by kailong on 2025/9/23*/import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.kailong.entity.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;
import java.util.Date;/*** 业务日志实体类* 对应表:biz_log*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("biz_log") // 指定MyBatis-Plus对应的表名
@Schema(description = "业务日志实体类,用于记录系统业务操作日志") // Swagger3类级别描述
public class BizLogEntity extends BaseEntity implements Serializable {//可以不继承BaseEntityprivate static final long serialVersionUID = 1L;/*** 日志ID(主键,自增)*/@TableId(value = "id", type = IdType.AUTO) // MyBatis-Plus主键注解,指定自增策略@Schema(description = "日志ID", example = "1") // Swagger3字段描述+示例值private Long id;/*** 方法名称(记录调用的业务方法名)*/@Schema(description = "方法名称", example = "getUserInfo")private String methodName;/*** 操作描述(记录业务操作的简要说明)*/@Schema(description = "操作描述", example = "查询用户信息")private String description;/*** 请求IP(记录发起请求的客户端IP地址)*/@Schema(description = "请求IP", example = "192.168.1.100")private String requestIp;/*** 浏览器类型(记录发起请求的浏览器信息,如Chrome、Firefox)*/@Schema(description = "浏览器类型", example = "Chrome 120.0.0.0")private String browser;/*** 请求地址(记录请求的URL路径,如/api/user/info)*/@Schema(description = "请求地址", example = "/api/user/info")private String url;/*** 请求参数(记录请求的参数信息,如{"userId":1})*/@Schema(description = "请求参数", example = "{\"userId\":1}")private String param;/*** 耗时(记录业务方法执行的耗时,单位:毫秒)*/@Schema(description = "耗时(毫秒)", example = "50")private Integer time;/*** 异常信息(记录业务方法执行过程中抛出的异常信息,无异常则为空)*/@Schema(description = "异常信息", example = "java.lang.NullPointerException: 用户不存在")private String exception;/*** 状态(1:成功 0:失败,记录业务操作的执行结果)*/@Schema(description = "状态(1:成功 0:失败)", example = "1")private int status;/*** 创建人ID(记录创建该日志的用户ID)*/@Schema(description = "创建人ID", example = "1001")private Long createUserId;/*** 创建人名称(记录创建该日志的用户名)*/@Schema(description = "创建人名称", example = "admin")private String createUserName;/*** 创建时间(记录日志的创建时间,默认为当前时间)*/@Schema(description = "创建时间", example = "2025-09-23 17:13:18")private Date createTime;/*** 修改人ID(记录最后修改该日志的用户ID,无修改则为空)*/@Schema(description = "修改人ID", example = "1002")private Long updateUserId;/*** 修改人名称(记录最后修改该日志的用户名,无修改则为空)*/@Schema(description = "修改人名称", example = "operator")private String updateUserName;/*** 修改时间(记录最后修改该日志的时间,无修改则为空)*/@Schema(description = "修改时间", example = "2025-09-23 17:15:30")private Date updateTime;/*** 是否删除(1:已删除 0:未删除,逻辑删除标记)*/@Schema(description = "是否删除(1:已删除 0:未删除)", example = "0")private Integer isDel;
}

BizLogMapper(用的MyBatisplus)

@Mapper
public interface BizLogMapper extends BaseMapper<BizLogEntity> {
}

BizLogService

public interface BizLogService {public void save(BizLogEntity bizLogEntity);
}

BizLogServiceImpl

@Service
public class BizLogServiceImpl implements BizLogService {@Autowiredprivate BizLogMapper bizLogMapper;@Overridepublic void save(BizLogEntity bizLogEntity) {FillUserUtil.fillCreateUserInfo(bizLogEntity);bizLogMapper.insert(bizLogEntity);}
}

测试效果

http://www.hskmm.com/?act=detail&tid=15563

相关文章:

  • [C++:类的默认成员函数——Lesson7.const成员函数] - 指南
  • 详细介绍:Xilinx系列FPGA实现12G-SDI音视频编解码,支持4K60帧分辨率,提供2套工程源码和技术支持
  • 使用 VMware Workstation 安装 CentOS-7 虚拟机
  • K12教育 和 STEAM教育
  • AT_arc167_c [ARC167C] MST on Line++
  • Lombok无法使用get set方法
  • redis的哈希扩容
  • vite tailwindcss配置
  • 在Vona ORM中实现多数据库/多数据源
  • 实用指南:python全栈-数据可视化
  • sql over()函数使用
  • Git回退版本 reset、revert、read-tree、restore
  • Avalonia 背景颜色Transparent在用户界面设计中对悬浮效果影响的总结
  • 飞书 燕千云焕新上线,飞书用户即刻试用ITSM工具
  • 如果使用微软 Azure 托管的 OpenAI 服务
  • Python类
  • 什么是文件外发审批?主要有哪几种关键流程?
  • VPX处理板设计原理图:9-基于DSP TMS320C6678+FPGA XC7V690T的6U VPX信号处理卡 C6678板卡, XC7VX690T板卡, VPX处理板
  • VitePress 添加友链界面
  • 跨网文件摆渡软件:企业数据安全高效传输的关键解决方案!
  • 洛谷题单指南-进阶数论-P1495 【模板】中国剩余定理(CRT)/ 曹冲养猪
  • 第十四届蓝桥杯青少组C++选拔赛[2022.12.18]第二部分编程题(4、充电站) - 指南
  • c语言之自定义memcpy
  • 国产芯片处理板卡:7-基于国产化FT-M6678+JFM7K325T的6U CPCI信号处理卡
  • 一文详解纷享销客CRM Agent平台3大核心能力(附应用场景与案例)
  • QOJ #5076. Prof. Pang and Ants 题解
  • 发现5个宝藏文件摆渡系统 2025年企业首选的摆渡方案是这个!
  • 漏洞挖掘实战:如何定制化模糊测试技术
  • nuxt3中使用pdfjs-dist实现pdf转换canvas实现浏览
  • 查看linux部署网站的TLS版本号