Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a try-with-resources statement for each line of log?

I want to log (append text) into a file every time something happens. I find this might be the correct way to do this with Java 7's try-with-resources statement:

public void log(String textLine) {
    try(PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("Logfile.txt", true)))) {
        output.println(textLine);
    }catch (IOException e) {
        //exception handling
    }
}

What I'm afraid of is that this log method gets called frequently and the output is closed and reopened each time this method gets called, which is unnecessary. At the same time, I want to benefit from Java 7's try-with-resources statement feature.

Is my concern not necessary because it's not an expensive operation to reopen and close a writer? Or I should use the Java 6's old fashioned way, i.e. handle exceptions manually and declare the output as a member field and close output manually when application ends?

like image 304
Kewei Shang Avatar asked Mar 16 '23 02:03

Kewei Shang


1 Answers

No, you should not open and close a FileWriter every time you want to append a new line to your log file.

You should:

  • open the log file at the start of the application
  • append to it
  • call flush()
  • and finally call close().

or if you want to use the try-with-resources statement then the code that calls the logger method should be put inside the body of the try-with-resources statement. Thanks to this you will not have to call the close() method as it will be called automatically.

However the best solution would be to, instead of reivnteting the wheel, use one of the existing, battle-tested, open source loggers such as log4j or logback, that cover all these internal details and expose a simple API that allows you to simply log a provided message.

like image 112
Adam Siemion Avatar answered Mar 29 '23 23:03

Adam Siemion