Java:如何使用类似日志记录的模式格式化字符串?

问题描述 投票:0回答:1

有时需要使用类似日志记录的模式组成字符串:

出了点问题,detailA={},detailB={}

但不是为了记录它,而是用于其他目的(例如通过网络发送)。

有时会导致代码重复,如下所示:

logger.info("Something went wrong, detailA={}, detailB={}", detailA, detailB));

otherSystem.info(String.format("Something went wrong, detailA=%s, detailB=%s",
  detailA, detailB);

这非常不方便且容易出错。如何使用日志记录模式和类似日志记录的 API 格式化字符串?

java string logging formatting string-formatting
1个回答
8
投票

如果您使用

slf4j
,则可以使用其
MessageFormatter.arrayFormat
,它会返回
FormattingTuple

FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);

然后将其转换为字符串。

String msg = ft.getMessage();

这意味着您可以为此添加一个实用方法

static String format(String format, String...params) {
    FormattingTuple ft = MessageFormatter.arrayFormat(format, params);
    String message = ft.getMessage();
    return message;
}

System.out.println(format("hi {}, you {}", "there", "rock"));
© www.soinside.com 2019 - 2024. All rights reserved.