Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I log a stacktrace using java's Logger class

I am using Java's Logger class. I want to pass ex.printStackTrace() into Logger.log(loglevel, String), but printStackTrace() returns void. So I am not able to pass and print the stack trace of the exception.

Is there any way that I can convert void into String, or are there any other methods to print the whole stack trace of exceptions?

like image 644
Surya Joseph Avatar asked Jul 14 '15 19:07

Surya Joseph


People also ask

How do you print Stacktrace in logs?

To print a stack trace to log you Should declare logger and method info(e. toString()) or log(Level.INFO, e. toString()). Logging is the process of writing log messages during the execution of a program to get error and warning messages as well as info messages.

Should Stacktrace be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.


1 Answers

You need to understand that void is actually nothingness. You cannot convert what is nothing. You might end up printing void as a string, but (trust me), you don't want that.

I think what you are looking for is

// assuming ex is your Exception object logger.error(ex.getMessage(), ex); // OR Logger.log(errorLogLevel, ex.getMessage(), ex) 

This will print the error message using the logger that you have configured. For more details, you can take a look at the java docs for Exception#getMessage()

like image 170
Saif Asif Avatar answered Sep 19 '22 06:09

Saif Asif