• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tibagni / LogViewer / #310

19 Oct 2026 12:08AM UTC coverage: 81.158% (-6.6%) from 87.738%
#310

push

github

web-flow
refactor: optimize code health across LogLineParser, LogParser, and FiltersList (#121)

- Extract date prefix parsing and fast-path timestamp parser in LogLineParser
- Deduplicate log entry flushing logic and isolate bugreport checks in LogParser
- Replace regex-based null character strip with fast literal replace in LogParser
- Decompose FiltersList into FilterListSearchHandler and FilterUIGroup
- Dismiss search popup on focus loss and handle Escape cancellation in FilterUIGroup
- Guard against null list selection when updating navigation action pane buttons
- Recreate search hint popup on query change with i18n ignore for Vim-style prefix
- Clear search highlight before triggering repaint in FilterListSearchHandler
- Guard empty group select-all checkbox from vacuous truth in FilterUIGroup
- Fix unmodifiable keySet mutation when updating filter groups in FiltersList
- Add unit tests in FiltersListTests with EDT discipline and headless assumptions

55 of 348 new or added lines in 4 files covered. (15.8%)

3084 of 3800 relevant lines covered (81.16%)

0.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.23
/src/main/java/com/tibagni/logviewer/log/parser/LogParser.java
1
package com.tibagni.logviewer.log.parser;
2

3
import com.tibagni.logviewer.ProgressReporter;
4
import com.tibagni.logviewer.log.*;
5
import com.tibagni.logviewer.logger.Logger;
6
import com.tibagni.logviewer.util.StringUtils;
7
import org.jetbrains.annotations.NotNull;
8

9
import java.io.File;
10
import java.nio.charset.Charset;
11
import java.nio.charset.StandardCharsets;
12
import java.util.*;
13
import java.util.regex.Matcher;
14
import java.util.regex.Pattern;
15

16
public class LogParser {
17
  // This is the maximum size of a payload log from Android
18
  private static final int LOGGER_ENTRY_MAX_PAYLOAD = 4068;
19
  // Even though Android limits its buffer for log payload to LOGGER_ENTRY_MAX_PAYLOAD
20
  // There are other parts of the log, like TAG, timestamp, pid, tid...
21
  // So, to be absolute sure we will not discard a valid log file because
22
  // of size restriction, set our maximum to twice the Android's payload size.
23
  public static final int MAX_LOG_LINE_ALLOWED = LOGGER_ENTRY_MAX_PAYLOAD * 2;
24

25
  private LogReader logReader;
26
  private List<LogEntry> logEntries;
27
  private ProgressReporter progressReporter;
28
  private final List<String> logsSkipped;
29
  private final Map<String, String> potentialBugReports;
30

31
  public LogParser(LogReader logReader, ProgressReporter progressReporter) {
1 ✔
32
    this.logReader = logReader;
1 ✔
33
    this.progressReporter = progressReporter;
1 ✔
34
    this.logEntries = new ArrayList<>();
1 ✔
35
    this.logsSkipped = new ArrayList<>();
1 ✔
36
    this.potentialBugReports = new HashMap<>();
1 ✔
37
  }
1 ✔
38

39
  public LogEntry[] parseLogs(Charset charset) throws LogReaderException {
40
    ensureState();
1 ✔
41

42
    logReader.readLogs(charset);
1 ✔
43
    Set<String> availableLogs = logReader.getAvailableLogPaths();
1 ✔
44

45
    int logsRead = 0;
1 ✔
46
    for (String log : availableLogs) {
1 ✔
47
      try {
48
        int progress = logsRead++ * 90 / availableLogs.size();
1 ✔
49
        progressReporter.onProgress(progress, "Reading " + log + "...");
1 ✔
50
        String logText = logReader.get(log);
1 ✔
51
        File logFile = logReader.getFile(log);
1 ✔
52
        List<LogEntry> logEntriesFromFile = getLogEntries(logText, log, logFile);
1 ✔
53

54
        if (!logEntriesFromFile.isEmpty()) {
1 ✔
55
          logEntries.addAll(logEntriesFromFile);
1 ✔
56
        } else {
57
          Logger.warning("Skipping " + log + " because it was empty");
1 ✔
58
          logsSkipped.add(log);
1 ✔
59
        }
60
      } catch(Exception e) {
×
61
        Logger.warning("Skipping " + log + " because it failed to parse", e);
×
62
        logsSkipped.add(log);
×
63
      }
1 ✔
64
    }
1 ✔
65

66
    LogEntry[] result = logEntries.toArray(new LogEntry[0]);
1 ✔
67

68
    if (availableLogs.size() > 1) {
1 ✔
69
      progressReporter.onProgress(91, "Sorting...");
1 ✔
70
      Arrays.parallelSort(result);
1 ✔
71
    }
72

73
    progressReporter.onProgress(95, "Setting index...");
1 ✔
74
    for (int i = 0; i < result.length; i++) {
1 ✔
75
      result[i].setIndex(i);
1 ✔
76
    }
77

78
    progressReporter.onProgress(100, "Completed");
1 ✔
79
    return result;
1 ✔
80
  }
81

82
  @NotNull
83
  public List<String> getLogsSkipped() {
84
    return logsSkipped;
1 ✔
85
  }
86

87
  @NotNull
88
  public Map<String, String> getPotentialBugReports() {
89
    return potentialBugReports;
1 ✔
90
  }
91

92
  @NotNull
93
  public Set<LogStream> getAvailableStreams() {
94
    ensureState();
1 ✔
95

96
    Set<LogStream> availableStreams = new HashSet<>();
1 ✔
97
    Set<String> availableLogsNames = logReader.getAvailableLogPaths();
1 ✔
98
    for (String logName : availableLogsNames) {
1 ✔
99
      availableStreams.add(LogStream.inferLogStreamFromName(logName));
1 ✔
100
    }
1 ✔
101

102
    return availableStreams;
1 ✔
103
  }
104

105
  private void ensureState() {
106
    if (logReader == null || logEntries == null || progressReporter == null) {
1 ✔
107
      throw new IllegalStateException("LogParser was already released. Cannot use it...");
×
108
    }
109
  }
1 ✔
110

111
  public void release() {
112
    logEntries.clear();
1 ✔
113
    logEntries = null;
1 ✔
114

115
    progressReporter = null;
1 ✔
116

117
    logReader.close();
1 ✔
118
    logReader = null;
1 ✔
119
  }
1 ✔
120

121
  private List<LogEntry> getLogEntries(String logText, String logPath, File logFile) {
122
    LogStream logStream = LogStream.inferLogStreamFromName(logPath);
1 ✔
123
    List<LogEntry> logLines = new ArrayList<>();
1 ✔
124

125
    String currentLogLine = null;
1 ✔
126
    int currentLineNumber = 0;
1 ✔
127
    StringBuilder continuationBuilder = null;
1 ✔
128

129
    int textLen = logText.length();
1 ✔
130
    int start = 0;
1 ✔
131
    int rawLineNumber = 0;
1 ✔
132
    while (start < textLen) {
1 ✔
133
      rawLineNumber++;
1 ✔
134
      int end = logText.indexOf('\n', start);
1 ✔
135
      if (end < 0) {
1 ✔
136
        end = textLen;
1 ✔
137
      }
138
      int lineEnd = end;
1 ✔
139
      if (lineEnd > start && logText.charAt(lineEnd - 1) == '\r') {
1 ✔
140
        lineEnd--;
×
141
      }
142
      String line = sanitizeLine(logText.substring(start, lineEnd));
1 ✔
143
      start = end + 1;
1 ✔
144

145
      if (isLogLine(line)) {
1 ✔
146
        flushPendingLogEntry(logLines, continuationBuilder, currentLogLine, logStream, logFile, currentLineNumber);
1 ✔
147
        continuationBuilder = null;
1 ✔
148

149
        currentLogLine = line;
1 ✔
150
        currentLineNumber = rawLineNumber;
1 ✔
151
      } else if (!shouldIgnoreLine(line) && currentLogLine != null) {
1 ✔
152
        // This is probably a continuation of an already started log line. Append to it
153
        if (continuationBuilder == null) {
1 ✔
154
          continuationBuilder = new StringBuilder(currentLogLine);
1 ✔
155
        }
156

157
        if (continuationBuilder.length() >= MAX_LOG_LINE_ALLOWED) {
1 ✔
158
          handleOversizedContinuation(continuationBuilder, logPath, logText);
1 ✔
159

160
          // We are done with this line, add it to the list and clear currentLogLine to avoid
161
          // executing this same code over and over for invalid lines
162
          logLines.add(createLogEntry(continuationBuilder.toString(), logStream, logFile, currentLineNumber));
1 ✔
163
          continuationBuilder = null;
1 ✔
164
          currentLogLine = null;
1 ✔
165

166
          // This could simply be a malformed line, just continue parsing other lines
167
          continue;
1 ✔
168
        }
169
        continuationBuilder.append(StringUtils.LINE_SEPARATOR).append(line);
1 ✔
170
      }
171
    }
1 ✔
172

173
    // Make sure to add the last log line as well
174
    flushPendingLogEntry(logLines, continuationBuilder, currentLogLine, logStream, logFile, currentLineNumber);
1 ✔
175

176
    return logLines;
1 ✔
177
  }
178

179
  /**
180
   * Strips trailing null characters if present to avoid false payload length errors.
181
   *
182
   * @param line the raw line text extracted from the log.
183
   * @return the sanitized line without null characters.
184
   */
185
  private String sanitizeLine(String line) {
186
    if (!line.isEmpty() && line.charAt(line.length() - 1) == '\u0000') {
1 ✔
NEW
187
      return line.replace("\u0000", "");
×
188
    }
189
    return line;
1 ✔
190
  }
191

192
  /**
193
   * Flushes the active log line or continuation buffer into the collected log entries list.
194
   *
195
   * @param logLines the list collecting parsed [LogEntry] instances.
196
   * @param continuationBuilder the builder holding multiline continuation text, or null.
197
   * @param currentLogLine the last single log line text, or null.
198
   * @param logStream the [LogStream] associated with this log.
199
   * @param logFile the source [File] being parsed, or null.
200
   * @param lineNumber the line number in the source file.
201
   */
202
  private void flushPendingLogEntry(
203
      List<LogEntry> logLines,
204
      StringBuilder continuationBuilder,
205
      String currentLogLine,
206
      LogStream logStream,
207
      File logFile,
208
      int lineNumber) {
209
    if (continuationBuilder != null) {
1 ✔
210
      logLines.add(createLogEntry(continuationBuilder.toString(), logStream, logFile, lineNumber));
1 ✔
211
    } else if (currentLogLine != null) {
1 ✔
212
      logLines.add(createLogEntry(currentLogLine, logStream, logFile, lineNumber));
1 ✔
213
    }
214
  }
1 ✔
215

216
  /**
217
   * Inspects and logs payload overflow for oversized continuation lines, detecting potential bug reports.
218
   *
219
   * @param continuationBuilder the continuation buffer exceeding allowable payload length.
220
   * @param logPath the path of the log file being parsed.
221
   * @param logText the full raw text of the log file.
222
   */
223
  private void handleOversizedContinuation(
224
      StringBuilder continuationBuilder,
225
      String logPath,
226
      String logText) {
227
    continuationBuilder.delete(MAX_LOG_LINE_ALLOWED, continuationBuilder.length());
1 ✔
228

229
    // First check if we have already considered this as a potential bugreport. If so,
230
    // don't waste any more time here
231
    if (!potentialBugReports.containsKey(logPath)) {
1 ✔
232
      // This could be a bugreport. If this is the case, keep track of it
233
      if (isPotentialBugReport(logText)) {
1 ✔
NEW
234
        Logger.info("Found a potential bugreport: " + logPath);
×
235

236
        // Make sure to remove all '\r' so it does not get in the way of the parsers
NEW
237
        String bugReportText = logText.replace("\r", "");
×
NEW
238
        potentialBugReports.put(logPath, bugReportText);
×
NEW
239
      } else {
×
240
        String incorrectLinePreview = continuationBuilder.substring(0, 100) + "...";
1 ✔
241
        Logger.warning(
1 ✔
242
            "Incorrect format on following line (too long - " + continuationBuilder.length() + " bytes):\n" +
1 ✔
243
                "\"" + incorrectLinePreview + "\"\n\n" +
244
                "Maximum logcat line should be " + LOGGER_ENTRY_MAX_PAYLOAD + " bytes");
245
      }
246
    }
247
  }
1 ✔
248

249
  private LogEntry createLogEntry(String logLine, LogStream logStream, File sourceFile, int lineNumber) {
250
    return LogLineParser.createLogEntry(logLine, lineNumber, logStream, sourceFile);
1 ✔
251
  }
252

253
  LogLevel findLogLevel(String logLine) {
254
    return LogLineParser.findLogLevel(logLine);
1 ✔
255
  }
256

257
  LogTimestamp findTimestamp(String logLine) {
258
    return LogLineParser.findTimestamp(logLine);
1 ✔
259
  }
260

261
  boolean isLogLine(String line) {
262
    return LogLineParser.isLogLine(line);
1 ✔
263
  }
264

265
  private boolean shouldIgnoreLine(String line) {
266
    return LogLineParser.shouldIgnoreLine(line);
1 ✔
267
  }
268

269
  private boolean isPotentialBugReport(String logText) {
270
    return logText.contains("Bugreport format version:");
1 ✔
271
  }
272
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc