Java logger to one file across multiple classes and packages

I am trying to figure out how to use the java.util.logging functions. All tutorials show how to log to a log file from the main class, but I cannot figure out how I can log to the same file in different classes. I have a web service and a web service client and I would like to be able to log errors to the web service when using the web service client.

I tried to create a log class, but I ended up with 38 empty log files. How do I create one log that gets called in each of my classes in the web service? The web service has two different packages and different classes.

In my search, I came across the idea of ​​a single logger class. I am 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, do I need to create a file handler in each class?

0


a source to share


1 answer


That the JDK logging framework has handlers for. Add a FileHandler to the logger which is at the root of your log hierarchy and everything will be written to that handler. You should make sure that the handlers have their own log levels too.



Thus, there is no need to implement your own logging system. Its already there and its already good. (And if you don't like JDK logging , use Apache Commons Logging with JDK logger or log4j .)

+2


a source







All Articles