4

I have a php script which is generating a log file. On the other hand I have another script that should be running hourly to process the logfile.

In my second script, I want to copy and truncate the log file while it's been writing to without any dataloss.

In a limited test I've been using rename, to create the copy and I getting the expected results

But I have concerns over the correctness of this approach.

Is this safe to do?

Cesar
  • 4,076
  • 8
  • 44
  • 68

1 Answers1

1

What you're doing is called "log rotation", and yes, it is safe to do it by renaming the log file.

  • In Linux, you can rename a file while another application is writing to it, and that application will continue writing to the renamed file. See this SO answer for details.

  • In Windows, you can only rename an open file if the application that opened it set the FILE_SHARE_DELETE flag when calling CreateFile. If the the flag is set, it works the same way it does on Linux (the application continues writing to the renamed file). If it's not set, any attempt to rename the file will fail.

You may also be interested in the logrotate command.

Community
  • 1
  • 1
Janis Elsts
  • 754
  • 3
  • 11