java - 在遍历日志文件条目时打印少量堆栈跟踪行

标签 java algorithm log4j

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

最终结果是这样的:

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

最佳答案

LineNumberReader是你的 friend 。

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 行,您需要跳转到外层循环,我会留给您解决这个问题。

关于java - 在遍历日志文件条目时打印少量堆栈跟踪行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13996000/

相关文章:

java - 运行应用程序时的警告

log4j - 为什么我们在 log4j.xml 中需要 root 和 logger

java - log4j 将标准输出重定向到 DailyRollingFileAppender

java - RxJava2 可观察背压

java - 无法在 eclipse 中连接到新的 SQL Server

c++ - 生成除循环旋转之外的所有排列

c# - 我解决 Misere Nim 游戏的缺陷在哪里

java - 在java中如何按频率然后按字母顺序对字符串进行排序?

java - 使用组合

python - Levinshtein 使用 Python 从文本文件中提取两个单词的距离