上次聊得spring 打日志 https://blog.csdn.net/u013476435/article/details/81984605
主要是通过 实现 MethodInterceptor 来实现的. 但是在Spring Boot, 注解的方式 更加低耦合 直接贴代码了.
package com.xxx.developer.service.config;
import com.alibaba.fastjson.JSON;
import com.xxx.common.annotation.NotNeedLog;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* @author 作者<LiuQi>
* @ClassName: MethodLogAdvice
* @Description: 自动打日志切面, 会自动将所切面的日志打印到控制台 以便于调试
* @date 2019年09月17日 10:13:07
* <p>
* 禁止使用格式化格式代码
*/
@Aspect
@Component
public class MethodLogAdvice {
/**
* @Fields : 字段最长输出设置,为了避免字符太长而刷屏
*/
public final Integer subLogLength = 3000;
/**
* @Fields : 环境设置
*/
@Value("${spring.profiles.active}")
private String environmentModel;
/**
* 拦截要执行的目标方法
* <p>
* 这里主要拦截 controller 以及 service 方法
*/
@Around(" execution(* com.jeejio.developer.service.*.controller..*(..))" +
"|| execution(* com.jeejio.developer.service.*.service..*(..))")
public Object joinpointMethod(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
StopWatch clock = new StopWatch();
clock.start(); //计时开始
//得到返回結果
result = joinPoint.proceed();
clock.stop(); //计时结束
//只有才dev 和local 才打印日志
if ("dev".equals(environmentModel) || "local".equals(environmentModel)) {
//太长的返回结果 予以过滤后返回
String resultJson = JSON.toJSONString(result);
Method method = null;
//通过父亲得到孩子的方法 得到其 注解
Class<?>[] objects = Arrays.stream(joinPoint.getArgs()).map(Object::getClass).toArray(Class[]::new);
method = joinPoint.getSourceLocation().getWithinType().getDeclaredMethod(joinPoint.getSignature().getName(), objects);
if (null != method) {
NotNeedLog notNeedLog = method.getAnnotation(NotNeedLog.class);
if (null != notNeedLog && notNeedLog.closeLogStatus()) {
//如果为true 那么就不需要打印日志
return result;
}
}
//方法参数类型,转换成简单类型
LoggerFactory.getLogger(joinPoint.getTarget().getClass()).info(
"耗时" + clock.getTotalTimeSeconds() + "秒|" + joinPoint.getSignature().getName() +
"|参数:" + JSON.toJSONString(joinPoint.getArgs()) +
" 结果:" + (StringUtils.isNotEmpty(resultJson) && resultJson.length() > subLogLength ?
resultJson.substring(0, subLogLength) + "......(已省略" + (resultJson.length() - subLogLength) + "个字符)"
: resultJson)
);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
效果如下