javasonarqubesonarqube-scansonarlintsonarlint-intellij

sonarLint: Invoke method(s) only conditionally


I have this piece of code:

logger.error("Unauthorized error: {} with request {} from {} ",
        authException.getMessage(),
        request.getServletPath(),
        getClientIp(request));

and:

  private static String getClientIp(HttpServletRequest request) {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }

I but I have this warning:

 Invoke method(s) only conditionally

Solution

  • You can check isErrorEnabled before logging.

    if (logger.isErrorEnabled())
        logger.error("Unauthorized error: {} with request {} from {} ",
            authException.getMessage(),
            request.getServletPath(),
            getClientIp(request));