springboot使用注解方式打印方法日志,可以很方便的打印日志,通用性很强。耦合很低,很好。
作为程序员的我不废话,咱们直接上代码
先创建个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ShowLog {
/**
* 日志描述
*/
String value();
/**
* 是否开启日志打印,默认true-开启
*/
boolean enabled() default true;
/**
* 是否打印请求参数
*/
boolean showArgs() default true;
/**
* 是否打印返回值
*/
boolean showResult() default true;
/**
* 是否打印耗时
*/
boolean showTime() default true;
}
利用spring的aop功能,整个环绕通知
@Slf4j
@Aspect
@Component
public class ShowLogHandler {
@Around("@annotation(showLog)")
public Object handle(ProceedingJoinPoint joinPoint, ShowLog showLog) throws Throwable {
if (!showLog.enabled()) {
return joinPoint.proceed();
}
boolean isSuccess = true;
long startTime = 0;
String desc = showLog.value();
String uuid = UUID.randomUUID().toString();
log.info(">>[{}]打印日志[{}]", uuid, desc);
try {
if (showLog.showTime()) {
startTime = System.currentTimeMillis();
}
if (showLog.showArgs()) {
String args = JsonUtil.getJsonStringOrNull(joinPoint.getArgs());
log.info(">>[{}][{}]参数[{}]", uuid, desc, args);
}
Object result = joinPoint.proceed();
if (showLog.showResult()) {
log.info("<<[{}][{}]方法返回值:[{}]", uuid, desc, JsonUtil.getJsonStringOrNull(result));
}
return result;
} catch (Throwable e) {
isSuccess = false;
log.error("<<[{}][{}]方法出错:[{}]", uuid, desc, e.getMessage());
throw e;
} finally {
if (showLog.showTime()) {
long endTime = System.currentTimeMillis();
log.info("<<[{}][{}]方法耗时[{}]毫秒,[{}]", uuid, desc, endTime - startTime, isSuccess);
}
}
}
}
标签:showLog,springboot,打印,boolean,注解,日志,true,String
From: https://blog.csdn.net/qq398581645/article/details/140011870