【Spring】SpringAop给所有Service增加日志

发布时间:2023年12月17日
@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======: " + className + "." + methodName + " with arguments: " + JSON.toJSONString(args));
            } catch (Exception e) {
                log.info("========ServiceLog==Param======: " + className + "." + methodName + " with arguments: " + 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======: " + className + "." + methodName + " with result: " + JSON.toJSONString(result));
            } catch (Exception e) {
                log.info("========ServiceLog==result======: error");
            }
        }
    }
}

其他的如controller同理

@Pointcut("within(@org.springframework.stereotype.Service *) || within(@org.springframework.stereotype.Controller *)")

还可以排除

@Pointcut("within(@org.springframework.stereotype.Service *) && !execution(* springfox.documentation.schema.property.*.*(..))")
文章来源:https://blog.csdn.net/zxcyxg123/article/details/135016259
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。