Search code examples
javaswingfileloggingfilehandler

Java Log File creates multiple copies


I am trying to create a logs file in a Java swings application that will contain all the messages generated by the code. But unfortunately it does not create 1 single log file but creates a structure as shown. I need 1 single log file.

enter image description here

My code:

 //get the logger object
logger = Logger.getLogger("MyLog");

try {
    // This block configure the logger with handler and formatter
    loggerFH = new FileHandler(System.getProperty("user.dir") + "\\resources\\logs\\logs.txt",true);
    logger.addHandler(loggerFH);            

    SimpleFormatter formatter = new SimpleFormatter();
    loggerFH.setFormatter(formatter);

} catch (IOException | SecurityException ex) {
    logger.severe(ex.getMessage());
    outputArea.append(ex.getMessage());

} 

Solution

  • I realized my Logger file was used by several instances at a time. So when 1 instance of filehandler locked the access to the file a new file was getting created. So I created a Synchronized class to handle all logging. And it worked great.

    public class SynchronizedLogger {
    
    //Logger to put error logs and messages in the log file
    
    public static Logger logger = Logger.getLogger("MyLog");
    
    
    //Logger Filehandler
    private static FileHandler loggerFH;
    
    public SynchronizedLogger() {
    }
    
    public static synchronized void writeLog(String message) {
        logger.info(message);
    }
    
    public SynchronizedLogger(int i) {
        try {
            synchronized (this) {
                // This block configures the logger with handler and formatter
                loggerFH = new FileHandler(System.getProperty("user.dir") + "\\resources\\logs\\logs.txt", 0, 1, true);
                logger.setUseParentHandlers(false);
                logger.addHandler(loggerFH);
    
                SimpleFormatter formatter = new SimpleFormatter();
                loggerFH.setFormatter(formatter);
            }
    
        } catch (IOException | SecurityException ex) {
            writeLog(ex.getMessage());
            outputArea.append("\n\n" + ex.getMessage());
    
        }
    }
    

    }