@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
LogEnum logEnum() default LogEnum.RUNTIME;
}
@Getter
@AllArgsConstructor
public enum LogEnum {
ACCESS("access", LogManager.getAccessLog()),
INTERFACE("interface", LogManager.getInterfaceLog()),
SYSTEM("system", LogManager.getSystemLog()),
RUNTIME("runtime", LogManager.getRuntimeLog()),
;
private String code;
private ILog log;
}
@Aspect
@Component
@Slf4j
public class LogAspect {
@Pointcut("@annotation(com.hahacloud.server.saas.service.iot.biz.service.annotation.Log)")
public void pointCut() {
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Log annotation = method.getAnnotation(Log.class);
if (null == annotation) {
return joinPoint.getArgs();
}
StringBuilder params = new StringBuilder();
String methodName = joinPoint.getSignature().getName();
Object[] argValues = joinPoint.getArgs();
String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
if (argValues != null) {
for (int i = 0; i < argValues.length; i++) {
params.append(argNames[i]).append(":").append(argValues[i]);
}
}
annotation.logEnum().getLog().info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{} 请求参数为: {}", methodName, JSON.toJSONString(params));
Object proceed = joinPoint.proceed();
annotation.logEnum().getLog().info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{} 响应参数为: {}", methodName, JSON.toJSONString(proceed));
return proceed;
}
@AfterThrowing(pointcut = "pointCut()", throwing = "e")
public void throwIng(JoinPoint joinPoint, Throwable e) {
String methodName = joinPoint.getSignature().getName();
LogManager.getRuntimeLog().error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{} 抛出异常为: {}", methodName, e);
}
}