In order to better understand how debug loggers work, I tried to implement my own logger in java. Shown in the code below. As far as I understand loggers are usually singletons. I want to use the same instance in different classes of my application. Each class where I use this logger will log to a different file. But that would mean that the singleton is being mutated by different objects. Wouldn't this cause inaccurately logging one classes debug output into a file that should be logged into by the other class. Since the same logger instance is shared across the entire app, how do different files get generated? Its the SAME instance being mutated in the application. So I decided to make the logFile location a final but then all classes would log to the same file. Could you shed some light on these curiosities?
Thank you in advance.
public class Logger {
private final String logFile;
private static Logger instance;
private Logger(String logFile){
this.logFile = logFile;
}
public Logger getInstance(String logFile){
synchronized(Logger.class){
if(instance==null){
instance = new Logger(logFile);
}
}
return instance;
}
public void write(String data) throws IOException{
PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter(logFile)));
out.write(data);
}
}
IF you want understand the logger implementation you can read the source code of log4j. But in log4j loggers are not singleton, there are multiple instances, it uses repository and factory patterns.