1

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.

Tom
  • 43,583
  • 4
  • 41
  • 61
vijaya kumar
  • 9
  • 1
  • 5

3 Answers3

4

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

try {
///some code here

} catch(Exception e) {
    logger.error("Error", e);
} //                      ^
Tom
  • 43,583
  • 4
  • 41
  • 61
  • Thanks for the reply it is not printing the entire stack just printing the name of the exception ex: null pointer exception etc,, – vijaya kumar Mar 15 '12 at 09:22
0

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()?

Community
  • 1
  • 1
amotzg
  • 1,142
  • 12
  • 28
0

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.

Dunes
  • 37,291
  • 7
  • 81
  • 97
  • it is not printing the entire stack in the log file it is just printing [2012-03-15 14:52:31,046] [ INFO] [http-0.0.0.0-8080-3] [exampleservice.java:500] - ERROR:Exceptoin name – vijaya kumar Mar 15 '12 at 09:26
  • @vijayakumar I made an edit that might help. But if there is no "DEBUG" output then your logger is not logging debug output and you need to fix your configuration. – Dunes Mar 15 '12 at 10:39