我有一个属性文件,用于放置错误消息。它们用于记录,但不仅仅是记录。
我遇到的麻烦是
MessageFormat.format(...)
和 slf4j
info, warn, error(...)
方法不共享相同的消息格式。{0}, {1}...
另一种 {}, {}...
在我的属性文件中,我只想拥有给定消息的一个版本:
MESSAGE_A
或 MESSAGE_B
(如下),但只有其中之一。
MESSAGE_A=Un numéro de compte {} a une nomenclature invalide: {}
MESSAGE_B=Un numéro de compte {0} a une nomenclature invalide: {1}
目前,如果我从上面的属性创建
String MESSAGE_A, MESSAGE_B...
并在下一个 Java 示例中使用它们,我将获得注释中的结果:
Logger LOGGER = LoggerFactory.getLogger(...)
LOGGER.warn(MESSAGE_A, "215756", "M85"); // Un numéro de compte 215756 a une nomenclature invalide: M85
LOGGER.warn(MESSAGE_B, "215756", "M85"); // Un numéro de compte {0} a une nomenclature invalide: {1}
MessageFormat.format(MESSAGE_A, "215756", "M85"); // Error or wrongly formatted message
MessageFormat.format(MESSAGE_B, "215756", "M85"); // Un numéro de compte 215756 a une nomenclature invalide: M85
我的解决方法是在名为
MessageFormat.format()
的方法中应用 LOGGER
:
LOGGER.warn(MessageFormat.format(MESSAGE_B, "215756", "M85"))
但它很笨拙。有没有更好的方法来解决这个问题?
您可以编写一个辅助方法,将一个“引擎”的格式字符串转换为另一个“引擎”的格式。在这种情况下,您可以编写一个转换器,通过将每个
java.text.MessageFormat
替换为 SLF4J
来将 {N}
格式转换为 {}
格式。该方法可能如下所示:
public static String toSLF4JFormat(String messageFormat) {
String regex = "\\{\\d+\\}";
String replacement = "{}";
String result = messageFormat.replaceAll(regex, replacement);
return result;
}
然后您可以在
LOGGER
调用中使用此辅助方法:
LOGGER.warn(FormatHelper.toSLF4JFormat(MESSAGE_B), "215756", "M85");
这样您只需要一种格式字符串(
MessageFormat
格式的字符串)。
您显然失去了重新排列
MessageFormat
中参数顺序的能力,或者您必须注意参数的顺序。当您有一个 (MessageFormat
) 日志字符串时,例如:
The system {1} does not support the type {2} while running in {0} mode.
会变成
The system {} does not support the type {} while running in {} mode.
并且参数的位置不再是
(1,2,0)
,而是正常顺序(0,1,2)
。为了使这项工作有效,您还必须重新排列 LOGGER.warn()
调用的参数:
MessageFormat.format(MESSAGE_FOOBAR, "DEBUG", "ACME", "int32");
LOGGER.warn(FormatHelper.toSLF4JFormat(MESSAGE_FOOBAR), "ACME", "int32", "DEBUG");