格式说明符应该在Java中替代字符串连接。

huangapple go评论76阅读模式
英文:

Format specifiers should be used instead of string concatenation in java

问题

我正在编写下面的代码:

Logger.error("文件 x 中出错:" + e.getMessage());

但是对于上面的代码行,我收到了一个错误,建议使用格式说明符而不是字符串连接。我应该如何修复它?

英文:

I am writing code the below code

Logger.error("Error in x file :",+ e.getMessage());

But for the above line of code I am getting the error to use format specifiers instead of string concatenation. How should I fix it?

答案1

得分: 1

private static final Logger logger = LoggerFactory.getLogger(YourClassName.class);

and try this:

logger.error("Error in x file {}", e.getMessage());

Logging this way, you avoid performance overhead for strings concatenation.

More about spring-boot logging configuration Zero Configuration Logging

英文:

Add to your class:

private static final Logger logger = LoggerFactory.getLogger(YourClassName.class);

and try this:

logger.error("Error in x file {}", e.getMessage());

Logging this way, you avoid performance overhead for strings concatenation.

More about spring-boot logging configuration Zero Configuration Logging

答案2

得分: -1

请参考以下翻译:

"Instead of concatenating the string with + (in "Error in x file :",+ e.getMessage()), you can use String.format to build the string instead:

Logger.error(String.format("Error in x file :%s", e.getMessage()));

Documentation on how Java String formatting works can be found here."

英文:

Instead of concatenating the string with + (in "Error in x file :",+ e.getMessage()), you can use String.format to build the string instead:

Logger.error(String.format("Error in x file :%s", e.getMessage()));

Documentation on how Java String formatting works can be found here.

huangapple
  • 本文由 发表于 2020年8月7日 17:11:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63298733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定