Reputation: 5198
Hi this is my CustomLogger class using java.util.Logger
public class CustomLogger {
private String pathToLogFiles = "/tmp/sos/logs/";
private Logger logger;
public CustomLogger(String prefix) {
logger = Logger.getLogger(prefix);
if( Utils.detectEnvironment() == Environment.LIVE ) {
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String filename = "log_" + date + ".txt";
FileHandler fileHandler = null;
try {
fileHandler = new FileHandler(this.pathToLogFiles + filename);
logger.addHandler(fileHandler);
fileHandler.setFormatter(new SimpleFormatter());
} catch (IOException e) {
logger.addHandler(new ConsoleHandler());
this.error(e.getMessage());
}
}
else {
logger.addHandler(new ConsoleHandler());
}
}
public void info(String message) {
logger.info(message);
}
public void error(String message) {
logger.warning(message);
}
}
When on Development Environment the logging to the console works fine, but on the live environment instead of logging to the one file as it should 12 different files are created containg a xml for every sent log message.
:/tmp/sos/logs# ls
log_2016-09-09.txt log_2016-09-09.txt.1.lck log_2016-09-09.txt.2.lck log_2016-09-09.txt.3.lck log_2016-09-09.txt.4.lck log_2016-09-09.txt.5.lck log_2016-09-09.txt.6.lck
log_2016-09-09.txt.1 log_2016-09-09.txt.2 log_2016-09-09.txt.3 log_2016-09-09.txt.4 log_2016-09-09.txt.5 log_2016-09-09.txt.6 log_2016-09-09.txt.lck
Can somebody tell me what is wrong there?
Thanks
Upvotes: 0
Views: 39
Reputation: 11045
Every time a CustomLogger constructor is executed you are creating and opening a new FileHandler. You need to ensure that you are only creating and adding the FileHandler once per JVM process.
Otherwise, you need to determine a proper time to close the previous FileHandler before opening a new FileHandler.
Upvotes: 1