I was implementing my Logger class but for a strange reason the constructor method is never called. In other class when I use SRCLogger.getLogger().log(Level.INFO, "Message"); there’s no log-file created on the path.
What am I missing? What’s wrong in this code?
Here’s my code:
public final class SRCLogger implements Serializable{
private static final Logger l = Logger.getLogger("mySRCLogger");
private FileHandler fh;
private String ROOT_DIR = "C:\\Users\\Test\\Desktop\\";
public SRCLogger(){
System.out.println("Constructor.");
try {
fh = new FileHandler(ROOT_DIR + "SRCLog.log");
fh.setFormatter(new SimpleFormatter());
l.addHandler(fh);
System.out.println("Try.");
} catch (IOException ex) {
Logger.getLogger(SRCLogger.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Catch IOException.");
} catch (SecurityException ex) {
Logger.getLogger(SRCLogger.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Catch SecurityException.");
}
}
public static Logger getLogger(){
return l;
}
}
Cheers and thanks in advance
Quite simply – you’re never calling the constructor. You’re calling this:
… which returns
l, a static field initialized like this:Why would you expect that to trigger your class to be instantiated? The fact that you don’t have any instance methods is also a design smell – what are you expecting the class to accomplish, other than adding a handler to an existing logger? If that’s all you want to do, I would change your class to just have a static method – you don’t really need any instances as far as I can tell.