【发布时间】:2017-07-17 19:34:31
【问题描述】:
我正在开发一个 RESTful 应用程序。应用程序任务之一是返回对应用程序进行的最后 10 个面向业务的 REST 调用以及请求信息和时间。这样做的最佳方法是什么?我读到了拦截器和过滤器。但我不确定这是否是个好主意...任何其他想法或信息如何实现这一点?
编辑: 我使用了执行器。 您回复后我的解决方案:
@Service
public class ActuatorTraceService {
private JsonParser jsonParser = new JsonParser();
private List<String> listWithInformationFromTrace = new ArrayList<>();
private JSONArray jsonArrayFromString;
private JSONArray listWithoutRequestAndTracePath;
public void takeInformationFromActuatorTrace() {
jsonArrayFromString = new JSONArray("[{}]");
String urlAddressForTrace = "http://localhost:8080/trace";
jsonArrayFromString = new JSONArray(jsonParser.takeJsonAsAStringFromUrl(urlAddressForTrace));
}
public String createPathForCheck(int i) {
String pathForCheck = jsonArrayFromString
.getJSONObject(i)
.getJSONObject("info")
.get("path")
.toString();
return pathForCheck;
}
public void createListWithoutRequestAndTracePath() {
listWithInformationFromTrace.clear();
takeInformationFromActuatorTrace();
listWithoutRequestAndTracePath = new JSONArray();
for (int i = 0; i < jsonArrayFromString.length(); i++) {
if (!createPathForCheck(i).equals("/request") &&
!createPathForCheck(i).equals("/trace")) {
listWithoutRequestAndTracePath.put(jsonArrayFromString.get(i));
}
}
}
public List<String> createListWithInformationsFromTrace(){
createListWithoutRequestAndTracePath();
for (int i=0; i<listWithoutRequestAndTracePath.length(); i++){
String timestampAndRequestInformation = takeTimestampFromTrace(i) + "\n" + takeRequestInformationFromTrace(i) + "\n";
listWithInformationFromTrace.add(timestampAndRequestInformation);
}
return listWithInformationFromTrace;
}
public String takeRequestInformationFromTrace(int i) {
return listWithoutRequestAndTracePath
.getJSONObject(i)
.getJSONObject("info")
.getJSONObject("headers")
.get("request")
.toString()
+ "\n";
}
public String takeTimestampFromTrace(int i) {
return jsonArrayFromString.getJSONObject(i).get("timestamp").toString() + "\n";
}
public String printLastTenRequestInformationFromTrace() {
StringBuilder stringToPrint = new StringBuilder();
createListWithInformationsFromTrace();
if (listWithInformationFromTrace.size() > 10) {
for (int i = 0; i < StaticValues.NUMBER_POSITION_TO_PRINT; i++) {
stringToPrint.append(listWithInformationFromTrace.get(i));
}
} else {
for (int i = 0; i < listWithInformationFromTrace.size(); i++) {
stringToPrint.append(listWithInformationFromTrace.get(i));
}
}
return stringToPrint.toString();
}
}
可能它的可读性更高,并且应该在最后实现漂亮的打印,但现在它可以工作。
【问题讨论】:
-
有很多方法可以做到这一点......从简单的“在每个休息方法中,将记录添加到静态(同步)列表”到更有趣的“将您的访问日志摄取到 ELK 和使用它的 REST API 查询它”
-
我还建议@erwin 以同样的方式将您的访问日志推送到 ELK 或 splunk 中,然后查询它以获得您想要的非功能性需求。
-
这可能无关紧要,因为您没有在任何地方提到 spring-boot。但是,如果您使用的是 spring boot 执行器,它的 /trace 端点会为您提供您正在寻找的详细信息。否则,您可以使用 spring AOP,如下面的答案之一所述。
标签: java spring rest spring-mvc