views:

854

answers:

1

I'm trying to figure out how to use the java.util.logging features. All of the tutorials show how to log to a log file from the main class, but I cannot figure out how I can log to one file in various classes. I have a web service and a web service client and I'd like to be able to log errors on the web service while using the web service client.

I tried creating a logger class but I ended up with 38 empty log files. How should I create one logger that's called in each of my classes on the web service? The web service has two different packages and various classes.

In my searching I've come across the idea for a singleton logger class. I'm trying to figure out how to implement it:

public class Logger{

private static Logger self = new Logger();

//empty private constructor
private Logger(){

}

//synchronized getInstance
public static synchronized Logger getInstance(){
 if (self == null)
  self = new Logger();
 return self;
}

//prevent cloning
public Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException(); 
}

//synchronized logging
public synchronized void debug(String msg){

}
public synchronized void info(String msg){

}
public synchronized void fatal(String msg){

}

}

To call this in my other classes, would I need to create a filehandler in each class?

+2  A: 

That’s what the JDK logging framework has Handlers for. Add a FileHandler to a logger that is at the root of your logger hierarchy and everything will be logged to that file handler. You have to watch out for the fact that handlers have their own log levels, too.

So, no need to implement your own logging framework. It’s already there, and it’s already good. (And if you don’t like the JDK logging, use Apache Commons Logging with the JDK logger or log4j.)

Bombe
What I'm trying to figure out is how to setup the "root" logger.If I have classes:client.alerts.AlertHandlerclient.alerts.AlertTimerclient.alerts.Connectclient.weather.Weatherclient.weather.WeatherDataWhat would I put in each of these so I could log to one file. Every example I find shows how to log from only one class to one log file. I don't know how to log from multiple classes to one log file. Where's the root of my "logger hierarchy"?
ravun
With the JDK a logger named “client” would be an appropriate root logger. You can also use Logger.getParent() to get a logger’s parent until a logger has no more parent. When you have your root logger, use Logger.addHandler() to add a handler to the logger. Finally adjust the handler’s log level (using Handler.setLevel()) and you should be all set.
Bombe