Skip to content

Instantly share code, notes, and snippets.

@lolson
Last active April 7, 2016 18:02
Show Gist options
  • Save lolson/852a050bad3284b5dd2bb43bb805a2d5 to your computer and use it in GitHub Desktop.
Save lolson/852a050bad3284b5dd2bb43bb805a2d5 to your computer and use it in GitHub Desktop.
Parse tomcat logs and insert them into a hashmap. Matches log entries that match a date timestamp regex and concatenates any subsequent detail log entries into a single line until it reaches the next entry starting with a date.
public class LogService {
private static HashMap<Integer, String> esbLogCache = new HashMap<Integer, String>();
private static String logDateRegex = "^[a-zA-Z]{3} (\\d)+, (\\d){4} (\\d)+:(\\d){2}:(\\d){2} (AM|PM).*";
static {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(getEsbLog()));
int row = 0;
boolean firstRead = true;
for (String line = br.readLine(); line != null; line = firstRead ? br.readLine() : line) {
StringBuilder sb = new StringBuilder();
firstRead = false;
if (line.matches(logDateRegex)) {
sb.append(line.trim());
sb.append(" ");
int detailLines = 0;
while ((line = br.readLine()) != null && !line.matches(logDateRegex)) {
if(detailLines < 10) { //don't include > 10 lines, spreadsheet cells have max cell contents of 32K char
sb.append(line.trim());
sb.append(" ");
detailLines++;
} else if (detailLines == 10) {
sb.append("...");
}
}
}
esbLogCache.put(row++, sb.toString());
}
} catch (FileNotFoundException e) {
print(e.getMessage());
} catch (IOException e) {
print(e.getMessage());
}
}
public static InputStream getEsbLog() throws FileNotFoundException {
String root = System.getenv("COF_CATALINA_HOME");
return new FileInputStream(new File(root + File.separator + "logs" + File.separator +"catalina.out"));
}
/**
* With given index range, returns list of selected log entries.
*
* @param start Starting index of log row number to retrieve
* @param end Ending index of log row number to retrieve
* @return
*/
public static List<String> retrieveLogView(int start, int end) {
List<String> logView = new ArrayList<String>();
int row = start;
while(row < end) {
logView.add(esbLogCache.get(row++));
}
return logView;
}
private static void print(String s) {
System.out.println(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment