I'm appending to a simple journal file, in which each line is an entry. Unfortunately, upon shutdown a partially written line is often present. The code looks like this:
private val out = java.nio.file.Files.newBufferedWriter(
java.nio.file.Paths.get(file),
java.nio.charset.StandardCharsets.UTF_8,
java.nio.file.StandardOpenOption.APPEND,
java.nio.file.StandardOpenOption.CREATE)
def write(s: String) = synchronized {
out.write(s)
out.newLine()
out.flush()
}
(Sorry about the Scala.)
I don't understand why a partial line would be in the file. The default buffer size I believe is 8 kB. The entries are shorter (<500 bytes). I flush after every write.
I have not been able to reproduce the partial lines — the problem happens at a client. But I am almost certain they simply send SIGTERM to the process to shut it down.
The log files written by SLF4J/LogBack/Log4j never have partial lines. What am I doing wrong? I looked in Apache Commons IO, hoping to find a guaranteed line-based Writer but did not.