vijaya kumar
vijaya kumar

Reputation: 9

Java with log4j

I have a code which throws exception and i can print the stack trace on the console and also in log file but i want it to be printed only on the log file and not on the console.

 try
    {
       ///some code here

    }
    catch(Exception e)
    {
        logger.error("Error", e.fillInStackTrace());
  }

try block throws some exception and i am logging it in the log file i am using log4J.jar fie

i tried printing just the object of Exception but it doesn't print the entire stack trace help me out with this.

Upvotes: 1

Views: 497

Answers (3)

Dunes
Dunes

Reputation: 40853

The perceived wisdom is that anything that logged at info level or greater will be printed to the console. Use trace or debug if you do not wish something to be printed to the console.

For instance you could try:

try
{
   // some code here
}
catch(Exception e)
{
    logger.error(e);
    // or maybe logger.error("descriptive message: " + e);

    logger.debug("Additional info on error", e);

    // if that fails you could try:
    StringWriter strWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(strWriter));
    logger.debug("Additional info on error", strWriter.toString());

    // or, I can't remember if you said fill in stack trace worked.
    // The point is that you should use debug to log the stack trace
    // as the information is to help you debug and isn't otherwise
    // useful information
    logger.debug("Additional info on error", e.fillInStackTrace());
}

I've added a fix so the stack trace should be printed. It's a little bit bulky, but since exceptions are meant to be rare it shouldn't add any appreciable overhead to your program.

Upvotes: 0

amotzg
amotzg

Reputation: 1202

You can try using getStackTrace() to get an array of StackTraceElement and build the string you desire from it.

But, if by "... it doesn't print the entire stack trace ..." you mean the the "... n more" line when looking at a stack trace with a "caused by" clause, look at this answer: Print full call stack on printStackTrace()?

Upvotes: 0

Tom
Tom

Reputation: 44881

You just need to pass the exception on the log call - as in:

try {
///some code here

} catch(Exception e) {
    logger.error("Error", e);
} //                      ^

Upvotes: 4

Related Questions