@Component
@Aspect
@Slf4j
public class ServiceLogAop {
@Pointcut("within(@org.springframework.stereotype.Service *)")
public void serviceMethods() {
}
@Before(value = "serviceMethods()")
public void logMethodEntry(JoinPoint joinPoint) {
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
if (args.length != 0) {
try {
log.info("========ServiceLog==Param======: {}.{} with arguments: {}", className, methodName, JSON.toJSONString(args));
} catch (Exception e) {
log.info("========ServiceLog==Param======: {}.{} with arguments: {}", className, methodName, Arrays.toString(args));
}
}
}
@AfterReturning(value = "serviceMethods()", returning = "result")
public void logMethodExit(JoinPoint joinPoint, Object result) {
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
if (args.length != 0) {
try {
log.info("========ServiceLog==result======: {}.{} with result: {}", className, methodName, JSON.toJSONString(result));
} catch (Exception e) {
log.info("========ServiceLog==result======: error");
}
}
}
@AfterThrowing(value = "serviceMethods()", throwing = "ex")
public void logAfterThrowing(JoinPoint joinPoint, Throwable ex) {
String className = joinPoint.getTarget().getClass().getSimpleName();
String methodName = joinPoint.getSignature().getName();
log.error("========ServiceLog==error======: {}.{} with error info: ", className, methodName, ex);
}
}
其他的如controller同理
@Pointcut("within(@org.springframework.stereotype.Service *) || within(@org.springframework.stereotype.Controller *)")
还可以排除
@Pointcut("within(@org.springframework.stereotype.Service *) && !execution(* springfox.documentation.schema.property.*.*(..))")