0

我正在创建一个日志过滤器应用程序,它将显示在应用程序日志中找到的所有错误条目的报告,我想知道将堆栈跟踪的几行与每个错误一起显示的最佳方法是什么。

最终结果将是这样的:

+ 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;
    }
4

1 回答 1

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 行,则需要中断到外部循环,我将留给您解决。

于 2012-12-21T19:50:08.490 回答