Re: Getting calling className in Java.Util.Logging.Logger
Gugle wrote:
I'm using Java 1.5 and I'm using Java's Logger class for logging. I
would like to know how to get the className and methodname of the
calling method for logging(like log4j does). For e.g., if I'm calling
the log method from method a of class B, then the log message should
contain the classname and method name. I don't want to pass the method
name and class name everytime to the log method. Can someone let me
know how this can be done?
Class name and method name are part of the default formatter.
But the following example show how you can control the output
yourself:
package december;
import java.util.Date;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class Logging {
public static void main(String[] args) {
Logger stdlogger = Logger.getLogger("Test 1");
stdlogger.info("This is a test");
Logger modlogger = Logger.getLogger("Test 2");
modlogger.setUseParentHandlers(false);
modlogger.addHandler(new ConsoleHandler());
modlogger.getHandlers()[0].setFormatter(new MyFormat());
modlogger.info("This is a test");
}
}
class MyFormat extends Formatter {
public String format(LogRecord rec) {
return ("class = " + rec.getSourceClassName() + "," +
"method = " + rec.getSourceMethodName() + "," +
"time = " + new Date(rec.getMillis()) + "," +
"message = " + rec.getMessage());
}
}
Arne