我正在创建一个日志过滤器应用程序,它将显示在应用程序日志中找到的所有ERROR条目的报告,我想知道什么是最好的方法来呈现堆栈跟踪的几行以及每个错误。
最终结果将是这样的:
+ ErrorA
- ErrorB
com.package.Class.method(Class.java:666)
com.package.AnotherClass.ADifferentMethodMethod(Class.java:2012)
com.thatOtherPackage.ThatClass.someOtherMethod(ThatClass.java:34)
+ ErrorC
这是我到目前为止所拥有的:
public JSONArray processFiles(File[] files){
FileReader fr = null;
BufferedReader br = null;
JSONObject jFiles = new JSONObject();
JSONArray jaf = new JSONArray();
try {
for (File file : files) {
jFiles.put("fileName", file.getName());
boolean fileIsOk = true;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
//Thanks to Windows, there's no way to check file.canRead()
//http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6203387
fileIsOk = false;
}
if(fileIsOk) {
br = new BufferedReader(fr);
String line = null;
JSONObject jLogEntries = new JSONObject();
JSONArray jalog = new JSONArray();
int lineNum = 0;
while ((line = br.readLine()) != null) {
if (line.contains("| ERROR |")) {
jLogEntries.put("line " + lineNum, line);
++lineNum;
}
**// TODO: Implement something to print the next 5 lines of the stack trace.**
}
lineNum = 0;
jalog.add(jLogEntries);
jFiles.put("logEntries", jalog);
jaf.add(jFiles);
}
}// end of files iteration
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return jaf;
}
答案 0 :(得分:2)
LineNumberReader是你的朋友。
LineNumberReadr lr = new LineNumberread(br);
while ((line = lr.readLine()) != null) {
if (line.contains("| ERROR |")) {
jLogEntries.put("line " + lr.getLineNumber(), line);
for (int i = 0; i < 5; i++) {
if ((line = lr.readLine()) != null) {
jLogEntries.put("line " + lr.getLineNumber(), line);
}
}
}
如果堆栈中少于5行,你需要打破外部循环,我会留给你解决这个问题。