use*_*710 8 java regex parsing exception
我有一个小系统,我想提供一个可以分析错误/异常并提出可能的解决方案的产品.
所以我想要一种解析java Exception的方法(因为我只在日志中使用它们[我不想影响实际的系统]).
解析之后,我想将它保存在数据库中,并将其与以前保存的异常(以某种格式)进行比较,以便找到最接近的匹配异常.
我想到了以下想法:"在D处C处的A处的XException"将保存为[XException,A,B,C,D],我将以某种方式在我的DB中搜索:[XException,?,?, ?]哪个最接近.例如:[XException,A,G,C,D]非常好.
您如何看待这些想法?
任何有效的方法来解析异常?
有效或更好的方法来定义两个例外之间的距离?
知道任何可以做到这一点的开源 - 我觉得没有找到任何.
谢谢.
这是一项非常艰苦的工作,但这里演示的是解析动态生成的一些实际异常.
码:
private static List<String> generate_$() {
List<String> returnValue = new LinkedList<String>();
Exception[] exceptions = { new ClassCastException(),
new NullPointerException(), new IOException("foo") };
for (Exception exception : exceptions) {
try {
throw exception;
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
returnValue.add(writer.getBuffer().toString());
}
}
return returnValue;
}
public static void main(String[] args) {
List<String> examples = generate_$();
for (String trace : examples) {
Pattern headLinePattern = Pattern.compile("([\\w\\.]+)(:.*)?");
Matcher headLineMatcher = headLinePattern.matcher(trace);
if (headLineMatcher.find()) {
System.out.println("Headline: " + headLineMatcher.group(1));
if (headLineMatcher.group(2) != null) {
System.out.println("Optional message "
+ headLineMatcher.group(2));
}
}
// "at package.class.method(source.java:123)"
Pattern tracePattern = Pattern
.compile("\\s*at\\s+([\\w\\.$_]+)\\.([\\w$_]+)(\\(.*java)?:(\\d+)\\)(\\n|\\r\\n)");
Matcher traceMatcher = tracePattern.matcher(trace);
List<StackTraceElement> stackTrace = new ArrayList<StackTraceElement>();
while (traceMatcher.find()) {
String className = traceMatcher.group(1);
String methodName = traceMatcher.group(2);
String sourceFile = traceMatcher.group(3);
int lineNum = Integer.parseInt(traceMatcher.group(4));
stackTrace.add(new StackTraceElement(className, methodName,
sourceFile, lineNum));
}
System.out.println("Stack: " + stackTrace);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Headline: java.lang.ClassCastException
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:16), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
Headline: java.lang.NullPointerException
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:17), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
Headline: java.io.IOException
Optional message : foo
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:17), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
Run Code Online (Sandbox Code Playgroud)