LogAspect
@Aspect
@Component
@Slf4j
public class LogAspect {
private static final String REQ_ID = "requestId";
@Pointcut("@annotation(com.demo.annotation.InsLog)")
public void pointcutInterface() {
}
@Pointcut("!execution(* com.demo.exclued*.*(..))")
public void excludePackage() {
}
@Pointcut("execution(* com.demo.rpc..*.*(..)) || execution(* com.demo.service..*.*(..)))")
public void pointcutPackage() {
}
@Around("(pointcutInterface() || pointcutPackage()) && excludePackage()")
public Object doAroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
Map<String, String> mdc = MDC.getCopyOfContextMap();
String key = joinPoint.getTarget().getClass().getSimpleName() + "#" + getMethodName(joinPoint) + "()";
Object[] args = joinPoint.getArgs();
String logDesc = "";
boolean reqLog = true,resLog = false, cost = true, throwEx = false;
InsLog insLog = getInsLog(joinPoint);
if (null != insLog) {
logDesc = insLog.desc();
reqLog = insLog.reqLog();
resLog = insLog.resLog();
cost = insLog.cost();
throwEx = insLog.throwEx();
}
String reqId = MDC.get(REQ_ID);
if (StringUtils.isBlank(reqId)) {
reqId = System.currentTimeMillis() + "-" + Arrays.hashCode(args);
MDC.put(REQ_ID, reqId);
}
Object res;
if (reqLog) {
log.info("【Log {}请求】{},参数={}", logDesc, key, JSONObject.toJSONString(args));
}
long beginMs = System.currentTimeMillis();
try {
res = joinPoint.proceed();
if (StringUtils.isBlank(MDC.get(REQ_ID))) {
MDC.setContextMap(mdc);
}
if (resLog) {
long costTime = 0L;
if (cost) {
costTime = System.currentTimeMillis() - beginMs;
}
log.info("【Log {}返回】{}{},结果={}", logDesc, key, costTime > 0L ? " 耗时=" + costTime + "ms" : "", JSONObject.toJSONString(res));
}
return res;
} catch (Exception e) {
if (!reqLog) {
log.error("【Log {}异常】{},参数={}", logDesc, key, JSONObject.toJSONString(args));
}
if (throwEx) {
log.error("【Log {}异常】{},处理异常", logDesc, key, e);
} else {
log.error("【Log {}请求】{},处理异常", logDesc, key);
}
throw e;
}
}
private InsLog getInsLog(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
if (signature instanceof MethodSignature) {
MethodSignature methodSignature = (MethodSignature) signature;
return methodSignature.getMethod().getAnnotation(InsLog.class);
}
return null;
}
private String getMethodName(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
if (signature instanceof MethodSignature) {
MethodSignature methodSignature = (MethodSignature) signature;
return methodSignature.getMethod().getName();
}
return "未获取到方法";
}
}
InsLog
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface InsLog {
String desc() default "";
boolean reqLog() default true;
boolean resLog() default false;
boolean cost() default true;
boolean throwEx() default true;
}