有没有一个字符串格式化程序,它将使用与SLF4J相同的语法?

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

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();

huangapple
  • 本文由 发表于 2020年9月20日 14:38:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63976213.html
匿名

发表评论

匿名网友

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

确定