背景
在日常的互联网项目开发中,经常会遇到前端调用服务接口,出现非预期的返回结果。尤其是接口参数过多,复杂度较高。对后端开发者排错调试,带来了极大的不便。
思路
- 请求参数
如果我们把接口的请求参数,通过json序列化记录到日志。然后直接使用序列化的日志作为调试的请求体,这样会极大减少我们构造参数的时间。 - 返回结果
把返回结果序列化到日志系统,然后通过查询日志,就可以找到出现问题时,服务返回的结果。
技术
AOP
https://www.jianshu.com/p/be6cb39dbeb7
https://github.com/ITfqyd/cxyxs
实现
创建俩个文件
- LogAble.java
- LogAspect.java
源码如下
package com.towen.common.annotation;
import org.springframework.boot.logging.LogLevel;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAble {
boolean logRequest() default true;
boolean logResponse() default false;
LogLevel level() default LogLevel.INFO;
String prefix() default "api";
}
package com.towen.common.annotation.aop;
import com.towen.common.annotation.LogAble;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogAspect {
private static final String separator = "_";
private static final String request = "request: ";
private static final String response = "response: ";
/**
* 切点
*/
@Pointcut("@annotation(com.ctrip.gs.comments.core.annotation.LogAble)")
public void pointCut() {
}
/**
* 环绕增强,相当于MethodInterceptor
*/
@Around("pointCut() && @annotation(logAble)")
public Object doAround(ProceedingJoinPoint joinPoint, LogAble logAble) throws Throwable {
Object res = null;
try {
logRequest(joinPoint, logAble);
res = joinPoint.proceed();
return res;
} finally {
logResponse(joinPoint, logAble, res);
}
}
private void logRequest(ProceedingJoinPoint joinPoint, LogAble logAble) {
if (joinPoint == null || logAble == null) {
return;
}
if (!logAble.logRequest()) {
return;
}
Object[] args = joinPoint.getArgs();
if (args == null || args.length == 0) {
return;
}
String logTitle = StringUtils.join(logAble.prefix(), separator, joinPoint.getSignature().getName());
String logValue = StringUtils.join(request, GsonUtil.serializeToJson(args.length == 1 ? args[0] : args));
LogUtil.logInfo(logTitle, logValue);
}
private void logResponse(ProceedingJoinPoint joinPoint, LogAble logAble, Object result) {
if (joinPoint == null || logAble == null) {
return;
}
if (!logAble.logResponse()) {
return;
}
String logTitle = StringUtils.join(logAble.prefix(), separator, joinPoint.getSignature().getName());
String logValue = StringUtils.join(response, GsonUtil.serializeToJson(result));
LogUtil.logInfo(logTitle, logValue);
}
}
注意:
LogUtil.java: 日志工具类
GsonUtil.java:json序列化工具类