I would like to log in my application which consist of several classes. I would like to have one .txt log file at the end. Therefore I make one static logger instance and I made
In MyLogging class, make the constructor private
instead of public
, and you need the following methods:
private static Logger getLogger(){
if(logger == null){
try {
new MyLogging();
} catch (IOException e) {
e.printStackTrace();
}
}
return logger;
}
public static void log(Level level, String msg){
getLogger().log(level, msg);
System.out.println(msg);
}
The log
method is static, so it can be called from any class using the class name.
So from all your classes, you can log just be invoking log method as below:
public class Test1 {
//static Logger logger; //no need to create an object for logging
public Test1()throws IOException {
MyLogging.log(Level.INFO, MyLogging.class.getName()); //call log method using classname
}