Reputation: 323
I have methods that are defined as...
public static void myMethod throws IOException ....
how can I use the Logger class to log the exception that is thrown to a file say named "test.log". I've heard of using logger.throwing... but it doesn't seem to work. Could anyone give me a step by step tip on how to do this? I just basically need to log the exception that is thrown (I didn't use try catches). Thank you so much!
Upvotes: 1
Views: 2603
Reputation: 105043
Try to use jcabi-aspects and its @LogException
annotation:
public class Resource {
@LogExceptions
public String load(URL url) {
return url.openConnection().getContent();
}
}
Upvotes: 0
Reputation: 14013
If you want a more automatic approach than the one given by user949300, you could take a look at Aspect-Oriented Programming (AOP), which allows you to do exception logging for all methods with just a little bit of code. Just google for aspectj log exceptions or java aop log exceptions.
See also question Audit Java: system to detect exceptions thrown / caught (aop?)
Upvotes: 0
Reputation: 15729
You'll need to add a catch clause. Below is a start for using the java.util.logging.Logger. Note that many projects use an Apache logger which is a bit more powerful and more complicated. Let's say you have a class com.myCompany.Foo that reads some file stuff
typically, at the start of the class in the static field declarations you will have
private static final Logger LOGGER = Logger.getLogger("com.myCompany.Foo");
then, when you have a method that throws exceptions (this is a stupid method!)
int readFirstCharOfFile(File f) throws IOException {
FileReader reader = null;
try {
reader = new FileReader(f);
return reader.read();
}
catch (IOException ioe) {
// You have a lot of possibilities here, but this seems most reasonable
LOGGER.log(Level.SEVERE, ioe.getMessage(), ioe);
// whether you rethrow the Exception "depends" on the contract, but, in our case
// the method declaration says that we do, so we do.
throw ioe;
}
finally {
if (reader != null)
reader.close();
}
}
The harder part is configuring the Logger to write where you want. IIRC, by default it goes to standard error. There is a lot of "magic" there that I never fully understood so I couldn't explain all the intricacies.
You can Google to get info, here are a couple useful links I found. link1 and link2
Upvotes: 2