participate


Reflections & Reference Objects - Logging stack trace in log4j
<<   Back to Forum  |   Give us Feedback
This topic has 3 replies on 1 page.
rgunder3
Posts:50
Registered: 3/5/00
Logging stack trace in log4j   
Mar 3, 2003 8:47 AM

 
Hi

I am using log4j in a webapp and it works fine except that I cant seem to log a stack trace: I would like to do someting like:

try {
blah blah
}
catch(Exception e) {
logger.error("Something bad happened: " + e.printStackTrace());
}

Obviously that will not work - but that's the kind of thing I want to do. I guess ideally it would be nice to pass the logger as a PrintStream argument e.g. printStackTrace(logger) but log4j's Logger class doesn't lend itself to this.

The only thing I can think is just to pass exception's 'message' to a standard log call, but this will not give me nearly as much info as the stack trace.

Any suggestions would be great

thanks
 
johan_abrandt
Posts:808
Registered: 10/11/99
Re: Logging stack trace in log4j   
Mar 3, 2003 8:52 AM (reply 1 of 3)  (In reply to original post )

 
Start by reading the javadoc?

logger.<level>( "this is a message", aThrowable );
 
jesper1
Posts:1,011
Registered: 1/23/01
Re: Logging stack trace in log4j   
Mar 4, 2003 5:52 AM (reply 2 of 3)  (In reply to original post )

 
I wrote a class ExceptionUtil to do this:
public class ExceptionUtil
{
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }
}

Use it like this:
try {
    // ...code that throws exception...
}
catch (Exception e) {
    logger.warn("Error while doing something: " + ExceptionUtil.getStackTrace(e));
}

Jesper
 
johan_abrandt
Posts:808
Registered: 10/11/99
Re: Logging stack trace in log4j   
Mar 4, 2003 5:55 AM (reply 3 of 3)  (In reply to #2 )

 
I wrote a class ExceptionUtil to do this:

Is there any reason why he shouldnt use the method already provided by Log4j?

logger.warn( "whatever", throwable );
 
This topic has 3 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 29
  • Guests : 132

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums