Java – eclipse – sonar s2629 may have false positives with new strings

I'm using the latest eclipse and sonar plug-ins

Record the following lines in answer:

log.debug("Request body: {}",new String(body,"UTF-8"));

String should be created only at debug level:

/**
 * Log a message at the DEBUG level according to the specified format
 * and argument.
 * <p/>
 * <p>This form avoids superfluous object creation when the logger
 * is disabled for the DEBUG level. </p>
 *
 * @param format the format string
 * @param arg    the argument
 */
public void debug(String format,Object arg);

But sonar labeled it squid: s2629:

An example is given to illustrate the connection

Is this a false positive sonar warning or did I miss something?

This is not a repetition of this question. It usually asks about the rule concept, that is, connecting, but not formatting to create an object as a new string

In addition, link replied that creating a new date () will not cause problems in the built-in format:

Solution

Downlink in non debug mode

log.debug("Request body: {}","UTF-8"));

replace

log.debug(messageformatter.format("Request body: {}","UTF-8")));

Avoid creating through messageformatter Format (string messagepattern, object ARG) creates a string, but does not create other strings created by the new string (body, "UTF-8")

This means that it is not a false positive because the parameters are calculated first before calling the logging method

As long as slf4j does not support lambda expression to lazy evaluate arguments (see comment by zhekakozlov), the following practical methods can be used as workarounds:

private static Object lazyToString(final supplier<String> stringsupplier) {
    return new Object() {
        @Override
        public String toString() {
            return stringsupplier.get();
        }
    };
}

This can be used to limit the conversion of byte arrays to strings to debug mode:

log.debug("Request body: {}",lazyToString(() -> new String(body,StandardCharsets.UTF_8)));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>