Search code examples
javascalalog4jlogbackstack-trace

How to get package data [jar file name] from stack trace?


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
}

Solution

  • 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));
    }