I’m new to java and trying to learn how to log an exception by example. I found the following example code here:
http://www.kodejava.org/examples/447.html
However, I don’t see where the filename for the log file is specified. When I research the question on Google usually people refer to the framework used for programming java to figure out where the log file gets stored. However, I’m not using a framework. I’m just creating my java files using VIM editor from the command line. The java file sits on an Linux CentOS application server and is called from a client’s browser.
Question 1: Is it possible to modify the example below to include a file name and path for logging? Or, am I way off base with this question?
Question 2: Even though I log the exception, will it still propagate to the client for the user to view? Hopefully it will, otherwise the user won’t know an error has occurred.
package org.kodejava.example.util.logging;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class LoggingException {
private static Logger logger = Logger.getLogger(LoggingException.class.getName());
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
try {
//
// Try to parsing a wrong date.
//
Date date = df.parse("12/30/1990");
System.out.println("Date = " + date);
} catch (ParseException e) {
//
// Create a Level.SEVERE logging message
//
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE, "Error parsing date", e);
}
}
}
}
Try this:
By default, a file handler overwrites the contents of the log file each time it is created. You might also want to append log file so in FileHandler constructor you need to specify
trueas a second parameter.Hope this helps.
EDIT:
This should work. I did not test it.
More efficient way would be create a method to initialize logger and add handler to it. But I will mostly recommend you to think about using
log4j. It is easy to set up and widely used logging framework.