Reputation: 343
I wanted to keep track of a Java project main activity logs for debugging in one log file. I used the following approach to open the existed file, and append the new content, but it seems to add another file adding 1,2,3 in front of the name every time I run my program. Although the logfile.log keeps updated, and stored the desired content. But, I couldn't figure out why the other logfile.log.2, logfile.log.3 ... files created
LoggerFile lf = new LoggerFile();
final FileHandler fh = new FileHandler(System.getProperty("user.dir")+"/logfile.log", 1024 * 1024, 1, true);
Logger logger = lf.initialize(fh);
logger.info("log file message ... ");
fh.close();
Here is how the LoggerFile looks like:
public class LoggerFile {
public LoggerFile() {
}
public Logger initialize(FileHandler fh) throws SecurityException, IOException{
Logger logger = Logger.getLogger("MyLog");//Logger.getLogger(UpdateExposureScores.class.getName());
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
return logger;
}
}
What seems to be wrong in the above code that it writes the log in several files? Thanks in advance.
Upvotes: 0
Views: 1148
Reputation: 11065
I assume you are using java.util.logging. From the j.u.l.FileHandler documentation:
Normally the "%u" unique field is set to 0. However, if the FileHandler tries to open the filename and finds the file is currently in use by another process it will increment the unique number field and try again. This will be repeated until FileHandler finds a file name that is not currently in use. If there is a conflict and no "%u" field has been specified, it will be added at the end of the filename after a dot. (This will be after any automatically added generation number.)
Opening multiple file handlers within the same process also has the same effect. Add lines to log the result of java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
and java.lang.management.ManagementFactory.getRuntimeMXBean().getStartTime()
so you can identify the JVMs that are creating the log files. You are either creating too many filehandlers pointing to the same location or you are starting multiple instances of your app.
You might want to look at the LogManager documentation which will explain alternate ways to configure your log settings.
Upvotes: 1