package com.casstime.ec.cloud.cart.infrastructure.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import com.casstime.commons.service.exception.HttpMessageException;
import com.casstime.commons.utils.JsonUtil;
import lombok.extern.log4j.Log4j2;
/**
* 监控配置
*/
@Aspect
@Component
@Log4j2
public class MonitoringActuator {
/**
* 打印含有@Log注解的方法的方法名、入参、出参、执行时长
*/
@Around("@annotation(com.casstime.ec.cloud.cart.infrastructure.aspect.Log)")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
String method = joinPoint.getSignature().getName();
log.info("method:{},args:{}",
() -> method,
() -> JsonUtil.serializer(joinPoint.getArgs()));
long begin = System.currentTimeMillis();
Object result = joinPoint.proceed();
log.info("method:{},execute times:{},result:{}",
() -> System.currentTimeMillis() - begin,
() -> JsonUtil.serializer(result));
return result;
}
/**
* 统一处理接口异常
*/
@AfterThrowing(throwing = "e",pointcut = "execution(public * com.casstime..ec.cloud.cart.interfaces.facade.*.*(..))")
public void handleException(JoinPoint joinPoint,Throwable e) {
if (e instanceof HttpMessageException) {
log.warn("{} error,() -> joinPoint.getSignature().getName(),() -> JsonUtil.serializer(joinPoint.getArgs()),() -> e);
}
}
}
package com.casstime.ec.cloud.cart.infrastructure.aspect;import static java.lang.annotation.ElementType.METHOD;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.Retention;import java.lang.annotation.Target;/** * 在方法上加上该注解,可以打印入参、出参和方法执行时长 */@Retention(RUNTIME)@Target(METHOD)public @interface Log {}