Martin
Martin

Reputation: 3058

How to show detail of Exception causes in log files

I have a logfile from Tomcat which shows the following error:

Caused by: java.lang.ClassNotFoundException: com.package.MyClass
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
... 33 more

The upper part of the Stacktrace (removed everything before the cause because it doesn't show the information I need) only shows Spring-internal classes. However, this error comes because someone forgot to report a transitive dependency for the war file...

Is there a way to configure Tomcat to show the hidden stacktrace lines?

Note: exception.getCause().printStacktrace() is not what I am looking for, I want all stacktraces to be printed in detail.

Upvotes: 1

Views: 1468

Answers (3)

codependent
codependent

Reputation: 24482

Don't really know how to configure it in Tomcat but, if the error is something that happens when initializing the Spring Servlet you can extend it and print the exception manually:

public class StartupErrorSafeDispatcherServlet extends DispatcherServlet {

    private Logger logger = ...

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            super.init(config);
        } catch (Throwable t) {
            System.out.println(ExceptionUtils.getStackTrace(t));
            logger.error("{}", ExceptionUtils.getStackTrace(t));
        }

    }

}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You can use the Guava library which provides a method getStackTraceAsString:

Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable. Note that you probably should not be parsing the resulting string; if you need programmatic access to the stack frames, you can call Throwable.getStackTrace().

You can also consider looking at Package java.util.logging something like

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "Exception", e2);

Upvotes: 0

codependent
codependent

Reputation: 24482

An alternative, use org.apache.commons.lang3.exception.ExceptionUtils:

ExceptionUtils.getStackTrace(Throwable th) 

gives you a String with the whole trace. Now you can print it the way you prefer

try{
    //something 
}catch(Exception exception){
    System.out.println(ExceptionUtils.getStackTrace(exception));
    logger.error("{}", ExceptionUtils.getStackTrace(exception));
}

Upvotes: 0

Related Questions