Spring boot项目实战之记录应用访问日志
1.说明
系统上线后往往我们需要知道都有哪些用户访问了应用的那些功能,以便更好的了解用户需求、防止恶意访问等。为此我们需要给应用添加记录访问日志的功能。下面就开始吧:
2.建表
CREATE TABLE `tb_operation_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`oper_module` varchar(100) DEFAULT NULL COMMENT '操作模块',
`oper_method` varchar(500) DEFAULT NULL COMMENT '操作方法',
`oper_type` varchar(500) DEFAULT NULL COMMENT '操作类型',
`oper_desc` varchar(1000) DEFAULT NULL COMMENT '操作描述',
`oper_param` varchar(1000) DEFAULT NULL COMMENT '请求参数',
`oper_ip` varchar(100) DEFAULT NULL COMMENT '请求参数',
`oper_uri` varchar(1000) DEFAULT NULL COMMENT '请求uri',
`create_time` datetime DEFAULT NULL COMMENT '操作时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=74 DEFAULT CHARSET=utf8 COMMENT='操作日志表';
省略了model/dao/service代码,如有疑问可以交流。
3.创建注解
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented
public @interface OperLog {
String operModule() default ""; // 操作模块
String operType() default ""; // 操作类型
String operDesc() default ""; // 操作说明
}
4.创建AOP(核心)
@Aspect
@Component
@Slf4j
public class OperLogAspect {
@Autowired
private OperationLogService operationLogService;
/**
* 操作日志切入点
*/
@Pointcut("@annotation(com.sgytech.wecms.common.annotation.OperLog)")
public void operLogPoinCut() {
}
/**
* 拦截用户操作日志
*
* @param joinPoint 切入点
* @param keys 返回结果
*/
@AfterReturning(value = "operLogPoinCut()", returning = "keys")
public void saveOperLog(JoinPoint joinPoint, Object keys) {
// 获取RequestAttributes
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// 从获取RequestAttributes中获取HttpServletRequest的信息
HttpServletRequest request = (HttpServletRequest) requestAttributes
.resolveReference(RequestAttributes.REFERENCE_REQUEST);
String requestIp = IpUtil.getRemoteIp(request);
// 本机访问的不记录日志
if(!"0:0:0:0:0:0:0:1".equals(requestIp)){
OperationLog operlog = new OperationLog();
try {
// 从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取切入点所在的方法
Method method = signature.getMethod();
// 获取操作
OperLog opLog = method.getAnnotation(OperLog.class);
if (opLog != null) {
String operModule = opLog.operModule();
String operType = opLog.operType();
String operDesc = opLog.operDesc();
operlog.setOperModule(operModule); // 操作模块
operlog.setOperType(operType); // 操作类型
operlog.setOperDesc(operDesc); // 操作描述
}
// 获取请求的类名
String className = joinPoint.getTarget().getClass().getName();
// 获取请求的方法名
String methodName = method.getName();
methodName = className + "." + methodName;
operlog.setOperMethod(methodName); // 请求方法
// 请求的参数
Map<String, String> rtnMap = converMap(request.getParameterMap());
// 将参数所在的数组转换成json
String params = JSON.toJSONString(rtnMap);
operlog.setOperParam(params); // 请求参数
operlog.setOperIp(IpUtil.getRemoteIp(request)); // 请求IP
operlog.setOperUri(request.getRequestURI()); // 请求URI
log.info("当前的记录是:"+methodName+params);
operationLogService.save(operlog);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 转换request 请求参数
*
* @param paramMap request获取的参数数组
*/
public Map<String, String> converMap(Map<String, String[]> paramMap) {
Map<String, String> rtnMap = new HashMap<String, String>();
for (String key : paramMap.keySet()) {
rtnMap.put(key, paramMap.get(key)[0]);
}
return rtnMap;
}
5.controller中使用
以我这个博客项目中的文章详情接口为例,我要记录每次用户查看文章的详情行为日志,可以这样用:
@OperLog(operModule = "文章详情",operType = "查询",operDesc = "查询文章详情")
@GetMapping("/{id}")
public String detail(@PathVariable Integer id, Model model, HttpServletRequest request){
// ...业务处理代码
}
6.呈现记录的日志
直接上图吧:
日志的话就一般只读就行了 搜索可以做的详细点多条件检索、时间范围检索,支持删除就是了。
分类:
Java项目实战
, # Spring-Boot
标签:
spring boot记录日志
, aop日志
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构