Correct replacing of log file

Do not leak resources in case of errors and ensure data is synced to
disk before replacing files.