java logger to one file over several classes and p

2019-08-20 12:35发布

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?

标签: java logging
1条回答
Fickle 薄情
2楼-- · 2019-08-20 13:11

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.)

查看更多
登录 后发表回答