1

I have three classes and I want to add the logs to a shared single file. So the constructor of each class has a

        fh = new FileHandler("log.txt", true);
        LOGGER_A.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter); 
    }
    catch (IOException ex) {
    }

     fh = new FileHandler("log.txt", true);
        LOGGER_B.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter); 
    }
    catch (IOException ex) {
    }

When I run the second constructor it creates a new file called "log.txt.1". How to avoid this, I want to use the log.txt file for all classes.

3 Answers 3

2

Add the same FileHandler object to both of your loggers.

FileHandler will try to get a lock on the filename so no other FileHandlers can use the same file. If the FileHandler is unable to get the lock, it appends increasing numbers to the end of the filename until it gets a unique lock on the file. Since your first FileHandler already has the lock on log.txt, the second FileHandler cannot get the same lock.

Sign up to request clarification or add additional context in comments.

1 Comment

Also make sure you use Java 8. One of the comments in stackoverflow.com/questions/14211629/… says handlers had a thread-safety bug until 8.
0

I think the problem you are presenting here is actually a feature.

From https://docs.oracle.com/javase/8/docs/api/java/util/logging/FileHandler.html

For a rotating set of files, as each file reaches a given size limit, it is closed, rotated out, and a new file opened. Successively older files are named by adding "0", "1", "2", etc. into the base filename.

So, as I see it all you have to do is to change the limit size of your log file :)

Comments

0

Don't forget to close the file after your FileHandler has logged.

With the close method from FileHandler Class:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.