前言
生产过程中,为了更好的辅助线上问题排查避免不了对接口出入参进行日志输出的时候,并且为了分析接口数据效果需要将每次请求接口的出入参进行落库方便后续的数据分析,这时总不能每个接口入参之后、出参之前都打印一遍日志吧?如果需要入库也总不能每个接口下面在调用一次入库方法吧?那这样做代码显的也太臃肿了,所以这时候我们通过注解的方式进行出入参的输出或入库,功能就变成了可插拔,会显得代码非常整洁,而且代码的可用性也会大大提高。一劳永逸,装逼神器。
1. 环境
JDK 1.8
springboot 2.7.15
2.依赖
java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.代码
3.1创建注解
java
package com.iterge.iterge_pre.annontation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author iterge
* @date 2023/11/10 15:04:36
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface SaveLogInfo {
}
3.2创建切面
java
package com.iterge.iterge_pre.aop;
import com.alibaba.fastjson2.JSONObject;
import com.iterge.iterge_pre.entity.Log;
import com.iterge.iterge_pre.service.ILogService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @author iterge
* @date 2023/11/10 15:06:46
*/
@Slf4j
@Component
@Aspect
public class SaveLogInfoAspect {
@Autowired
private HttpServletRequest request;
@Autowired
private ILogService iLogService;
@SneakyThrows
@Around("@annotation(com.iterge.iterge_pre.annontation.SaveLogInfo)")
public Object saveLog(ProceedingJoinPoint point){
//获取请求路径
String requestURI = request.getRequestURI();
//获取请求参数
Object[] args = point.getArgs();
String req = JSONObject.toJSONString(args);
log.info("请求参数:{}",req);
//获取响应参数
String proceed = JSONObject.toJSONString(point.proceed());
log.info("响应参数:{}",proceed);
try {
saveLog(req,proceed,requestURI);
int a = 10/0;
}catch (Exception e){
log.info("方法出入参入库失败!");
}
return point.proceed();
}
private void saveLog(String req,String res,String url){
Log logInfo = new Log();
logInfo.setReq(req);
logInfo.setRes(res);
logInfo.setUrl(url);
try{
iLogService.save(logInfo);
}catch (Exception e){
log.error("日志保存失败,req:{},res{}",req,res,e);
}
}
}
3.3测试接口
java
@GetMapping("/test")
@SaveLogInfo
public Response<String> test(@RequestParam String name){
String s = iUserInfoService.saveLog(name);
return Response.ok(s);
}