Tuesday, February 14, 2012

Preventing Java from printing the stack trace on certain exceptions


I have a security class that throws an AccessDeniedException on a user not being authorized for a certain operation. I made it even neat and put a msg in there with the info I need.



The problem is that now my logs are full of stack traces for every single time I throw. I don't care to see the stack trace for THIS exception, and the stack traces are bloating my logs.



Is there a way to tell Java not to print the stack trace to the logs if it's this exception?



Thanks!



--



llappall

4 comments:

  1. The problem is that now my logs are full of stack traces


    This is like saying "my fire alarm keeps going off, how can I make it quieter?". There are only two good courses of action.


    Determine that these are false alarms, and alter your alarm system so it is not so sensitive to events that are not actually dangerous. The throwing of an exception does not indicate a bug, or even anything very remarkable, if it is a checked exception. Even if a checked exception is worth logging, the stacktrace will not be worth logging, because a stacktrace is useful only for debugging.
    Determine that the alarms are genuine, in which case find out why fires keep breaking out and fix whatever is igniting them. That is, getting fixing the bugs that cause exceptions to be thrown. If you have many bugs that flood your log file it does not matter which you fix first, so just fix whichever are easiest to read in the log file

    ReplyDelete
  2. You need to investigate where you are catching (if catching) this exception, and ensure that you don't log the exception, but only the message...

    ReplyDelete
  3. Either you can decide to catch that particular exception and don't do anything about it.
    Either you can set the UncaughtExceptionHandler on the current Thread.

    Thread.currentThread().setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)


    and in the handle you perform an instanceof on the exception to see if it is that particular exception

    ReplyDelete
  4. I don't know if this will help you with your logging, but if you are creating an Exception purely to improve the logic and readability of your code, and if you never expect to wonder where the heck it came from, then override the fillInStackTrace() method, like so:

    public class AccessDeniedException extends Exception {
    public synchronized Throwable fillInStackTrace() { return this; }
    }


    This will improve your program's performance--dramatically if you throw a lot of them. It won't eliminate logging. The other answers should help with that, but if they don't your log messages will be much reduced.

    ReplyDelete