SonarLint警告:Invoke method(s) only conditionally问题求助
解决SonarLint「Invoke method(s) only conditionally」警告
这个警告的核心原因是:当前代码会无条件执行日志参数里的所有方法调用(比如authException.getMessage()、request.getServletPath()、getClientIp(request)),哪怕logger的error级别未开启。这些不必要的方法调用会带来额外性能开销,尤其是getClientIp还涉及请求头读取和分支判断逻辑。
下面是两种可靠的解决方式:
方式一:先判断日志级别再执行日志逻辑
通过logger.isErrorEnabled()判断当前是否开启了error级别的日志,只有当级别开启时,才执行参数方法并打印日志,避免无效计算:
if (logger.isErrorEnabled()) { logger.error("Unauthorized error: {} with request {} from {} ", authException.getMessage(), request.getServletPath(), getClientIp(request)); }
如果request存在为null的可能,还需要额外处理空指针风险:
if (logger.isErrorEnabled()) { String servletPath = request != null ? request.getServletPath() : "null"; String clientIp = getClientIp(request); logger.error("Unauthorized error: {} with request {} from {} ", authException.getMessage(), servletPath, clientIp); }
方式二:使用SLF4J延迟加载参数(推荐SLF4J 1.8.0+)
SLF4J 1.8.0及以上版本支持用Supplier接口包装参数,日志框架会在确认需要输出日志时,才调用Supplier.get()执行参数计算,写法更简洁:
logger.error("Unauthorized error: {} with request {} from {} ", () -> authException.getMessage(), () -> request.getServletPath(), () -> getClientIp(request));
同样,若request可能为null,可以在Supplier里加入空判断:
logger.error("Unauthorized error: {} with request {} from {} ", () -> authException.getMessage(), () -> request != null ? request.getServletPath() : "null", () -> getClientIp(request));
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

