0

In the logback library, they have a way to get "stack traces with packaging data" (package and package versions).

Example:

java.lang.Exception: 99 is invalid
  at path.to.MyClass.myFunc(MyClass.java:431) [struts-1.2.9.jar:1.2.9]

How do I get "struts-1.2.9.jar" from a line in a stack trace?

Is there a method in Java or Scala that does this?

String getPackageName(String lineInTrace) {
    ...
    return packageName
}
Michael Lafayette
  • 2,972
  • 3
  • 20
  • 54

2 Answers2

2

Try this

for (StackTraceElement el : e.getStackTrace()) {
    Class<?> clazz = Class.forName(el.getClassName());
    String location = clazz.getProtectionDomain().getCodeSource().getLocation().toString();
    System.out.println(location.substring(location.lastIndexOf('/') +1));
}
Evgeny
  • 2,483
  • 1
  • 17
  • 24
0

The stuff in the square brackets are the module name and version, in Java 9 and above. You can get the module name using StackTraceElement.getModuleName().

It seems that if you are not using modules, the jar file name is used instead of the module name.

Karsten Spang
  • 161
  • 2
  • 10