0

I would like to save the stacktrace of exceptions to a mysql database using JDBC appender. The issue here is I don't want to use e.printstacktrace in my code. Is there a way to go about?

kozmo
  • 4,024
  • 3
  • 30
  • 48
Pubudu
  • 478
  • 1
  • 6
  • 22
  • Yes, use a logging library. And given you tagged log4j, you already know about their existence, so what is your real question? – Mark Rotteveel Feb 02 '18 at 10:00
  • I'm using DB appender and saving logs into a table. But I would like to save Exceptions with it's stacktrace into my database. When I use the following code it does not save the stack trace into my table. What's the recommended way of saving a stack trace as an error log into a table? catch (Exception e) { log.error(" ::: An exception occurred :::: " + e); } – Pubudu Feb 04 '18 at 07:36
  • Have you even looked at the log4j API? There are log methods that explicitly take a `Throwable` (the super-class of exceptions), or if they take multiple object parameters, then you put the exception last. – Mark Rotteveel Feb 04 '18 at 10:15
  • See also: https://stackoverflow.com/questions/15805460/how-to-print-an-exception-using-logger – Mark Rotteveel Feb 04 '18 at 10:28

1 Answers1

0

Managed to convert the stacktrace to a string by using ExceptionUtil class. Once the stacktrace is converted to a string I was able to save the error log using the DB appender as described below.

try{
    //Some code that throws an exception
    }

catch(SomeException e)
    {
    String stackTrace = ExceptionUtils.getStackTrace(e);
    log.error(":: An error has occurred :::: " + stackTrace);
    }
Pubudu
  • 478
  • 1
  • 6
  • 22