加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Eclipse – Sonar S2629可能带有新String的误报

发布时间:2020-12-15 08:27:51 所属栏目:Java 来源:网络整理
导读:我正在使用最新的 Eclipse和Sonar插件 在answer中记录以下行: log.debug("Request body: {}",new String(body,"UTF-8")); 只有在DEBUG级别时才应创建String: /** * Log a message at the DEBUG level according to the specified format * and argument. *
我正在使用最新的 Eclipse和Sonar插件

在answer中记录以下行:

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

只有在DEBUG级别时才应创建String:

/**
 * 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);

但是Sonar将它标记为鱿鱼:S2629:

“Preconditions” and logging arguments should not require evaluation (squid:S2629)

并举例说明连接

logger.log(Level.DEBUG,“Something went wrong: ” + message); // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages

这是一个假阳性声纳警告还是我错过了什么?

这不是this question的重复,它通常询问规则概念,即连接,但不是格式化创建对象作为新String

另外link的回答说创建新的Date()不会产生内置格式的问题:

06002

Logging this way,you avoid performance overhead for strings concatenation when nothing should be actually logged.

解决方法

在非DEBUG模式下行

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

代替

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

避免创建通过MessageFormatter.format(String messagePattern,Object arg)创建的字符串,但不创建由新String(正文,“UTF-8”)创建的其他字符串.

这意味着它不是误报,因为在调用日志记录方法之前首先计算参数.

只要SLF4J does not support lambda expression to lazy evaluate arguments(见comment by ZhekaKozlov),可以使用以下实用方法作为变通方法:

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

这可以用于限制将字节数组转换为字符串到DEBUG模式:

log.debug("Request body: {}",lazyToString(() -> new String(body,StandardCharsets.UTF_8)));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读