英文:
Is there a string formatter that will use the same syntax as SLF4J?
问题
我(显然)熟悉String.format()
和MessageText.format()
两者——我也理解在Slf4j
日志记录中使用的字符串格式化语法;令人沮丧的是它们都不同且不兼容。
我正在寻找的是一个类似于MessageText.format()
的函数,它能像slf4j日志记录器的格式化器一样工作,这样我就可以在日志消息和(例如)异常消息中都使用相同的字符串常量:
public static String THIS_HAPPENED =
"Unfortunately, foo was {}, but bar ({}) was not";
// ...
if (someDisaster(foo, bar)) {
log.error(THIS_HAPPENED, foo, bar);
throw new IllegalStateException(MessageText.betterFormat(THIS_HAPPENED,
foo, bar));
}
不幸的是,MessageText
需要位置指示符({0}
),而Slf4j对此极为反感。
在这方面是否有一些解决方案?
(显然,显然!)我可以自己编写这个方法,但如果已经有比我更优秀的程序员已经完成了,我愿意使用那个方法。
非常感谢!
英文:
I am (obviously) familiar with both String.format()
and MessageText.format()
- I also understand the string formatting syntax used in Slf4j
logging; it is frustrating that they are all different and incompatible.
What I am looking for is a MessageText.format()
-like function, that works exactly as the slf4j loggers' formatters, so I can use the same String constants both in log messages and in (for example) exception messages:
public static String THIS_HAPPENED =
"Unfortunately, foo was {}, but bar ({}) was not";
// ...
if (someDisaster(foo, bar)) {
log.error(THIS_HAPPENED, foo, bar);
throw new IllegalStateException(MessageText.betterFormat(THIS_HAPPENED,
foo, bar));
}
Unfortunately, MessageText
needs the position specifier ({0}
) and Slf4j positively hates it.
Is there something out there that does this?
(Obviously, obviously!, I can write the method myself, but if it's already been done by coders better than I, I would happily use that instead).
Many thanks in advance.
答案1
得分: 1
尝试一下:
import org.slf4j.helpers.MessageFormatter;
在这里你有:
MessageFormatter.format(messagePattern, arg).getMessage();
英文:
Try to:
import org.slf4j.helpers.MessageFormatter;
there you have:
MessageFormatter.format(messagePattern, arg).getMessage();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论