[英]How can I capture Java exceptions, including the stack trace, from a log file using grep?
[英]pattern for reading particular stack trace from log file in java
我正在使用BufferedReader
讀取日志文件,並且想從日志文件中提取特定的堆棧跟蹤。 但是,我無法讀取它,輸出為空。
例如,我有一個例外:client和它的堆棧跟蹤如下:
java.sql.SQLException:“字段列表”中的未知列“ client”
SELECT查詢
在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)在com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)在com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666) )com.mysql.jdbc.Connection.execSQL(Connection.java:2994)com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:936)com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java: 1030)在telemed.admin.DAO.DAO.AdminDAO.getTeleVisitorData(AdminDAO.java:87)在telemed.admin.AdminService.getTeleVisitors(AdminService.java:31)在org.apache.jsp.jsp.telemed.telemedResponse_jsp._jspService(telemedResponse_ .java:330),位於org.apache.jasper.servlet的javax.servlet.http.HttpServlet.service(HttpServlet.java:728),位於org.apache.jasper.runtime.HttpJspBase.java(70)。 org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)的org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)的JspServletWrapper.service(JspServletWrapper.java:432) .servle org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)的t.http.HttpServlet.service(HttpServlet.java:728)org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java: 210)在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
我正在嘗試讀取其中具有特定單詞但不在異常行中的特定單詞的堆棧跟蹤。
我的代碼是:
BufferedReader br=new BufferedReader(new FileReader("E:/exp.txt"));
String temp;
Pattern expPattern=Pattern.compile("(?s).*Exception:.*client.*[\\n\\r].*");
while((temp=br.readLine())!=null){
//System.out.println("line::::"+temp);
Matcher headlineMatcher=expPattern.matcher(temp);
if(headlineMatcher.find()){
System.out.println("=>"+temp);
temp=null;
}
}
您的方法的問題是readLine()
返回的行沒有任何行尾字符。 因此,您無法匹配它們。
一種可能的解決方案是匹配第一行並打印固定數量的后續行,或者直到找到可以標識為您感興趣的最后一行的行。
將該片段作為簡單演示。
Pattern expPattern = Pattern.compile("(?s).*Exception:.*client.*");
int followingLines = 4;
try (BufferedReader br = Files.newBufferedReader(Paths.get("exp.txt"), UTF_8)) {
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (expPattern.matcher(line).find()) {
System.out.println("=>" + line);
for (int i = 0; i < followingLines; i++) {
line = br.readLine();
if (line == null) {
break;
}
System.out.println("=>" + line);
}
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
輸出是。
=>java.sql.SQLException: Unknown column 'client' in 'field list'
=>
=>SELECT query
=>
=>at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928) at ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.