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?
No, you should not open and close a FileWriter
every time you want to append a new line to your log file.
You should:
flush()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With