通过格式说明符动态传递值给字符串格式化器



我试图打印每个请求的参数不断变化的日志。我正在尝试使用字符串格式化程序。

我的代码

MailService.java

static final LinkedHashMap<String , String> logMap = new LinkedHashMap<String , String>();
logMap.put("mailType", mailType);
logMap.put("projectId", projectId);
LogUtility.getDownstreamReqLog(LOGGER,jwtTokenProvider,url,logMap);

LogUtility.java

public static void getDownstreamReqLog(Logger log, JwtTokenProvider jwtTokenProvider, URI url,LinkedHashMap<String,String> logMap) {
String message = " {" + BffConstants.REQUEST_ID_KEY + " = %s }" + " {" + BffConstants.REQUEST_URL + " = %s }";
List<String> values = new ArrayList<>();
String mapKeys = "";
for (String key : logMap.keySet()) {
mapKeys = mapKeys + " {" + key + " =%s }";
values.add(logMap.get(key));
}
message = message + mapKeys;
LogUtility.info(log, message,jwtTokenProvider.getRequestId(),url,values.toArray(new
String[0]));
}
public static void info(Logger log, String message, Object... args) {
log.info(getFormattedMessage(message, args));
}
private static String getFormattedMessage(String message, Object... args) {
String formattedMessage = message;
if (args != null && args.length > 0) {
formattedMessage = String.format(message, args);
}
return formattedMessage;
}

请求Id键和Url对于所有请求都是通用的。其他参数根据请求而变化。所以我试图动态地追加键和值对的日志信息方法。键按预期传递。但我面临的问题是价值是作为一个数组。是否有一种方法,我可以通过它作为单独的字符串数组会导致格式化错误。例如,对象数组args接受如下格式的输入

[0] = "requestId"
[1] = "url"
[2] = String[2]

我希望它以这种格式传递

[0] = "requestId"
[1] = "url"
[2] = "value1"
[3] = "value2"
and so on... based on number of values present in LinkedHashMap so that respective formatter key gets mapped to respective value. 

有一种方法,我可以完成它在getDownstreamReqLog方法,或者我必须开始考虑在getFormattedMessage方法本身的变化,如果它不可能传递值作为单独的字符串而不是数组?谢谢你的建议。

您可以将您的requesttid和url添加到您的值列表中,并仅使用您的数组调用LogUtility.info

public static void getDownstreamReqLog(Logger log, JwtTokenProvider jwtTokenProvider, URI url,LinkedHashMap<String,String> logMap) {
String message = " {" + BffConstants.REQUEST_ID_KEY + " = %s }" + " {" + BffConstants.REQUEST_URL + " = %s }";
List<String> values = new ArrayList<>();
values.add(jwtTokenProvider.getRequestId()); 
values.add(url.toString());
String mapKeys = "";
for (String key : logMap.keySet()) {
mapKeys = mapKeys + " {" + key + " =%s }";
values.add(logMap.get(key));
}
message = message + mapKeys;
LogUtility.info(log, message, values.toArray(new String[0]));
}

相关内容

  • 没有找到相关文章

最新更新