springboot 前后端处理日志

为了实现一个高效且合理的日志记录方案,我们需要在系统架构层面进行细致规划。在某些情况下,一个前端页面可能会调用多个辅助接口来完成整个业务流程,而并非所有这些接口的交互都需要被记录到日志中。为了避免不必要的日志开销,并确保日志系统的可读性和有效性,我们可以采用以下策略:

日志记录策略概述
前端控制:
前端在发起请求时,可以通过HTTP头(Header)传递一个标志,指示当前请求是否需要记录日志。例如,可以使用一个自定义的Header,如operation-log,其值可以是true或false。
后端响应:
后端服务接收到请求后,首先检查该Header的存在及值。如果该Header存在且其值为true,则后端将记录此次请求的相关信息;反之,则忽略日志记录。
下面贴出核心代码
注解

import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Loggable {// 接口信息String value() default "";// 是否记录响应结果,默认为trueboolean logResponse() default true;// 模块String module() default "";// 类型 insert 新增 delete 删除  select 查看 update 修改String type() default "";}

配置信息

import cn.com.nmd.base.constant.Constants;
import cn.hutool.core.util.IdUtil;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class TraceIdFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String traceId = IdUtil.objectId();MDC.put(Constants.TRACE_ID, traceId);try {// 响应头中添加 traceId 参数,方便排查问题response.setHeader(Constants.TRACE_ID, traceId);filterChain.doFilter(request, response);}finally {MDC.remove(Constants.TRACE_ID);}}}
import cn.com.nmd.auth.log.mdc.TraceIdFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;@Configuration
@ConditionalOnWebApplication
public class TraceIdAutoConfiguration {@Beanpublic FilterRegistrationBean<TraceIdFilter> traceIdFilterRegistrationBean() {FilterRegistrationBean<TraceIdFilter> registrationBean = new FilterRegistrationBean<>(new TraceIdFilter());registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);return registrationBean;}}

工具类

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;public class WebUtils extends org.springframework.web.util.WebUtils {/*** 获取 ServletRequestAttributes* @return {ServletRequestAttributes}*/public static ServletRequestAttributes getServletRequestAttributes() {return (ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes());}/*** 获取 HttpServletRequest* @return {HttpServletRequest}*/public static HttpServletRequest getRequest() {return getServletRequestAttributes().getRequest();}/*** 获取 HttpServletResponse* @return {HttpServletResponse}*/public static HttpServletResponse getResponse() {return getServletRequestAttributes().getResponse();}}

拦截器

import cn.com.nmd.auth.annotation.Loggable;
import cn.com.nmd.auth.utils.SecurityUtils;
import cn.com.nmd.auth.utils.WebUtils;
import cn.com.nmd.base.constant.Constants;
import cn.com.nmd.base.model.SysOperationLog;
import cn.com.nmd.base.utils.IpUtils;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;@Aspect
@Component
public class LogAspect {private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);private final List<Class<?>> ignoredParamClasses = ListUtil.toList(ServletRequest.class, ServletResponse.class,MultipartFile.class);// 定义切入点,匹配带有 @Loggable 注解的方法@Pointcut("@annotation(cn.com.nmd.auth.annotation.Loggable)")public void loggableMethod() {}@Around("loggableMethod()")public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {// 获取 RequestHttpServletRequest request = WebUtils.getRequest();String operateLog = request.getHeader("operation-log");// 开始时间long startTime = System.currentTimeMillis();SysOperationLog sysOperationLog = null;boolean b = false;if ("true".equals(operateLog)) {// 获取目标方法MethodSignature signature = (MethodSignature) joinPoint.getSignature();Method method = signature.getMethod();Loggable loggable = method.getAnnotation(Loggable.class);b = loggable.logResponse();sysOperationLog = this.buildLog(loggable, joinPoint);}Throwable throwable = null;Object result = null;try {result = joinPoint.proceed();return result;} catch (Throwable e) {throwable = e;throw e;} finally {if ("true".equals(operateLog)) {// 操作日志记录处理this.handleLog(startTime, sysOperationLog, throwable, b, result);}}}private void handleLog(long startTime, SysOperationLog sysOperationLog, Throwable throwable, boolean b, Object result) {try {// 结束时间long executionTime = System.currentTimeMillis() - startTime;// 执行时长sysOperationLog.setOperateTime(executionTime);// 执行状态String logStatus = throwable == null ? Constants.SUCCESS : Constants.FAIL;sysOperationLog.setStatus(logStatus);// 执行结果if (b) {Optional.ofNullable(result).ifPresent(x -> sysOperationLog.setResult(JSON.toJSONString(x)));}else {sysOperationLog.setResult(("{\"code\": \"200\",\"message\": \"\",\"data\": \"\"}"));}// 保存操作日志logger.info("保存的日志数据:{}", JSON.toJSONString(sysOperationLog));} catch (Exception e) {logger.error("记录操作日志异常:{}", JSON.toJSONString(sysOperationLog));}}private SysOperationLog buildLog(Loggable loggable, ProceedingJoinPoint joinPoint) {HttpServletRequest request = WebUtils.getRequest();SysOperationLog operationLog = new SysOperationLog();operationLog.setIp(IpUtils.getIpAddr(request));operationLog.setMethod(request.getMethod());operationLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));operationLog.setUri(URLUtil.getPath(request.getRequestURI()));operationLog.setType(loggable.type());operationLog.setModule(loggable.module());operationLog.setTraceId(MDC.get(Constants.TRACE_ID));operationLog.setCreateTime(new Date());operationLog.setParams(getParams(joinPoint));operationLog.setCreateUserId(SecurityUtils.getUserId());return operationLog;}/*** 获取方法参数** @param joinPoint 切点* @return 当前方法入参的Json Str*/public String getParams(ProceedingJoinPoint joinPoint) {// 获取方法签名Signature signature = joinPoint.getSignature();String strClassName = joinPoint.getTarget().getClass().getName();String strMethodName = signature.getName();MethodSignature methodSignature = (MethodSignature) signature;logger.debug("[getParams],获取方法参数[类名]:{},[方法]:{}", strClassName, strMethodName);String[] parameterNames = methodSignature.getParameterNames();Object[] args = joinPoint.getArgs();Method method = ((MethodSignature) signature).getMethod();if (ArrayUtil.isEmpty(parameterNames)) {return null;}Map<String, Object> paramsMap = new HashMap<>();for (int i = 0; i < parameterNames.length; i++) {Object arg = args[i];if (arg == null) {paramsMap.put(parameterNames[i], null);continue;}Class<?> argClass = arg.getClass();// 忽略部分类型的参数记录for (Class<?> ignoredParamClass : ignoredParamClasses) {if (ignoredParamClass.isAssignableFrom(argClass)) {arg = "ignored param type: " + argClass;break;}}paramsMap.put(parameterNames[i], arg);}// 特别处理 @RequestBody 参数for (int i = 0; i < parameterNames.length; i++) {Object arg = args[i];if (arg != null && method.getParameterAnnotations()[i].length > 0) {RequestBody requestBodyAnnotation = method.getParameterAnnotations()[i][0].annotationType().getAnnotation(RequestBody.class);if (requestBodyAnnotation != null) {paramsMap.put(parameterNames[i], arg);}}}String params = "";try {// 入参类中的属性可以通过注解进行数据落库脱敏以及忽略等操作params = JSON.toJSONString(paramsMap);} catch (Exception e) {logger.error("[getParams],获取方法参数异常,[类名]:{},[方法]:{}", strClassName, strMethodName, e);}return params;}
}

示例

 	@Loggable(value = "保存采集信息", type = "insert", module = "业务管理-场站管理", logResponse = true)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/881400.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于STM32的简易交通灯proteus仿真设计(仿真+程序+设计报告+讲解视频)

基于STM32的简易交通灯proteus仿真设计(仿真程序设计报告讲解视频&#xff09; 仿真图proteus 8.9 程序编译器&#xff1a;keil 5 编程语言&#xff1a;C语言 设计编号&#xff1a;C0091 **1.**主要功能 功能说明&#xff1a; 以STM32单片机和数码管、LED灯设计简易交通…

无人自助超市系统小程序源码开发

随着科技的飞速发展和消费模式的转变&#xff0c;无人自助超市作为一种新兴的商业模式&#xff0c;以其便捷性、高效率以及对“体验式购物”的完美诠释&#xff0c;受到了广泛关注。本文renxb001将深入探讨无人自助超市系统小程序源码开发的核心环节和技术要点。 一、系统需求分…

RNN--详解

RNN 1. 概述 循环神经网络 (Recurrent Neural Network, RNN) 是一种专门用于处理序列数据的神经网络模型。与传统的前馈神经网络不同&#xff0c;RNN 具有循环结构&#xff0c;能够处理时间序列和其他顺序依赖的数据。其关键在于可以利用前一个时刻的信息&#xff0c;通过隐状…

红帽7—Mysql路由部署

MySQL Router 是一个对应用程序透明的InnoDB Cluster连接路由服务&#xff0c;提供负载均衡、应用连接故障转移和客户端路 由。 利用路由器的连接路由特性&#xff0c;用户可以编写应用程序来连接到路由器&#xff0c;并令路由器使用相应的路由策略 来处理连接&#xff0c;使其…

Jedis多线程环境报错:redis Could not get a resource from the pool 的主要原因及解决办法。

本篇文章主要讲解&#xff0c;Jedis多线程环境报错&#xff1a;redis Could not get a resource from the pool 的主要原因及解决办法。 作者&#xff1a;任聪聪 日期&#xff1a;2024年10月6日01:29:21 报错信息&#xff1a; 报文&#xff1a; redis Could not get a resou…

云原生日志ELK( logstash安装部署)

logstash 介绍 LogStash由JRuby语言编写&#xff0c;基于消息&#xff08;message-based&#xff09;的简单架构&#xff0c;并运行在Java虚拟机 &#xff08;JVM&#xff09;上。不同于分离的代理端&#xff08;agent&#xff09;或主机端&#xff08;server&#xff09;&…

Spring Boot驱动的现代医院管理系统

1系统概述 1.1 研究背景 如今互联网高速发展&#xff0c;网络遍布全球&#xff0c;通过互联网发布的消息能快而方便的传播到世界每个角落&#xff0c;并且互联网上能传播的信息也很广&#xff0c;比如文字、图片、声音、视频等。从而&#xff0c;这种种好处使得互联网成了信息传…

【斯坦福CS144】Lab5

一、实验目的 在现有的NetworkInterface基础上实现一个IP路由器。 二、实验内容 在本实验中&#xff0c;你将在现有的NetworkInterface基础上实现一个IP路由器&#xff0c;从而结束本课程。路由器有几个网络接口&#xff0c;可以在其中任何一个接口上接收互联网数据报。路由…

【uniapp小程序】使用cheerio去除字符串中的HTML标签并获取纯文本内容

【uniapp小程序】使用cheerio去除字符串中的HTML标签并获取纯文本内容 参考资料安装引入使用 参考资料 【博主&#xff1a;AIpoem】uniapp小程序 使用cheerio处理网络请求拿到的dom数据 cheerio文档&#xff1a;https://github.com/cheeriojs/cheerio/wiki/Chinese-README 安…

Sequelize 做登录查询数据

在 Sequelize 中处理登录请求通常意味着你需要根据提供的用户名或电子邮件以及密码来查询数据库中的用户。由于密码在数据库中应该是以哈希形式存储的&#xff0c;因此你还需要验证提供的密码是否与存储的哈希密码匹配。 以下是一个简单的例子&#xff0c;展示了如何使用 Sequ…

SpringBoot美发门店系统:提升服务质量

摘要 随着信息技术在管理上越来越深入而广泛的应用&#xff0c;管理信息系统的实施在技术上已逐步成熟。本文介绍了美发门店管理系统的开发全过程。通过分析美发门店管理系统管理的不足&#xff0c;创建了一个计算机管理美发门店管理系统的方案。文章介绍了美发门店管理系统的系…

SpringBoot访问web中的静态资源

SpringBoot访问web中的静态资源&#xff0c;有两个方式&#xff1a; 1、SpringBoot默认指定了一些固定的目录结构&#xff0c;静态资源放到这些目录中的某一个&#xff0c;系统运行后浏览器就可以访问到 ① 关键是SpringBoot默认指定的可以存放静态资源的目录有哪些&#xff…

U mamba配置问题;‘KeyError: ‘file_ending‘

这个错误仍然是因为在 dataset_json 中找不到 file_ending 键。请尝试以下步骤&#xff1a; 检查 JSON 文件&#xff1a;确认 JSON 文件中确实有 file_ending&#xff0c;并且它的拼写完全正确。 打印 JSON 内容&#xff1a;在抛出异常之前&#xff0c;添加打印语句输出 datas…

JavaScript 数组简单学习

目录 1. 数组 1.1 介绍 1.2 基本使用 1.2.1 声明语法 1.2.2 取值语法 1.2.3 术语 1.3 案例 1. 数组 1.1 介绍 1.2 基本使用 1.2.1 声明语法 1.2.2 取值语法 1.2.3 术语 1.3 案例

Python知识点:如何应用Python工具,使用NLTK进行语言模型构建

开篇&#xff0c;先说一个好消息&#xff0c;截止到2025年1月1日前&#xff0c;翻到文末找到我&#xff0c;赠送定制版的开题报告和任务书&#xff0c;先到先得&#xff01;过期不候&#xff01; 如何使用NLTK进行语言模型构建 在自然语言处理&#xff08;NLP&#xff09;中&a…

pikachu靶场总结(三)

五、RCE 1.RCE(remote command/code execute)概述 RCE漏洞&#xff0c;可以让攻击者直接向后台服务器远程注入操作系统命令或者代码&#xff0c;从而控制后台系统。 远程系统命令执行 一般出现这种漏洞&#xff0c;是因为应用系统从设计上需要给用户提供指定的远程命令操作的…

基于SpringBoot和Vue的餐饮管理系统

基于springbootvue实现的餐饮管理系统 &#xff08;源码L文ppt&#xff09;4-078 第4章 系统设计 4.1 总体功能设计 一般个人用户和管理者都需要登录才能进入餐饮管理系统&#xff0c;使用者登录时会在后台判断使用的权限类型&#xff0c;包括一般使用者和管理者,一…

星融元P4交换机:在全球芯片短缺中,为您的网络可编程之路保驾护航

当数字化转型成为新常态&#xff0c;云计算、物联网、5G和人工智能等技术正以惊人的速度进步&#xff0c;重塑了我们对网络设备性能和适应性的预期。在这场技术革新的浪潮中&#xff0c;网络的灵活性、开放性和编程能力成为了推动行业发展的关键。P4可编程交换机&#xff0c;以…

飞驰云联入围2024西门子Xcelerator公开赛50强

近日&#xff0c;备受瞩目的西门子 Xcelerator公开赛公布结果&#xff0c;经过激烈的筛选&#xff0c;Ftrans飞驰云联《Ftrans制造业数据交换安全管控解决方案》凭借优异的表现&#xff0c;成功入围 Xcelerator公开赛50强&#xff01; Xcelerator 公开赛以工信部智能制造典型场…

胤娲科技:00后揭秘——AI大模型的可靠性迷局

当智能不再“靠谱”&#xff0c;我们该何去何从&#xff1f; 想象一下&#xff0c;你向最新的GPT模型提问&#xff1a;“9.9和9.11哪个大&#xff1f;”这本应是个小菜一碟的问题&#xff0c;却足以让不少高科技的“大脑”陷入沉思&#xff0c; 甚至给出令人啼笑皆非的答案。近…