Reliable method for writing a log file

I´m operating a Kirby 2.x site for a client, that he uses to manage tickets in a repair shop. About 20 of his employes use the site, to track customer requests and to send template based mails regarding repair status etc. to the customers.

Now my client would like to log some of the key activities on the website (for example opening of a ticket, closing of a ticket, notification mail sent to customer) in an overall logfile for statistical purposes.

My idea is, to write a simple logfile and add new entries with f::append().

My question is: Is this a reliable method to capture really all events? What happens, if two events happen at exactly the same time? Will both log entries be written into the log file, or ist the file locked, when writing one entry with the f::append() method?

Many thanks in advance for any input or alternative ideas how to reliably write a log file.

At some point in the past I asked myself the same question. I cannot give you a definitive and authoritive answer but some things to consider:

  1. The f::append method is using the PHP function file_put_contents with the LOCK_EX flag, which will ask for an exclusive lock on the given file. The lock is blocking any other request, hence any simultaneous call will wait.

  2. PHP uses advisory locks, which means if a process is writing to a file and has the lock, it says to others “please respect this and wait” but if other processes do not care, there is nothing to hinder them to access the file in question.

  3. While only 20 users are working with the system, chances for simultaneous writes are rather low.

  4. You could mitigate the risk of simultaneous writes with your design. If, for instance, you create a logfile for each case, identified by a case id or something else, chances for simultaneous writes are much lower or ruled out completely if a case is only edited by one employee at a time.

  5. You could think about writing the log entriess to a database system which will take care of simultaneous writes by its own. This might even have the advantage of faster operations since all kind of file operations should be considered as slow. Of course, the overall volume of your activities counts.

1 Like

@Adspectus

Thank you very much for your insightful reply!

Your no. 2. is especially interesting: I will change/add to the log file only with the f::append method, can one therefore assume, that the underlying file_put_contents function respects the LOCK_EX flag, that was set by an other process, that used the same function?

Yes, I would assume that the function will respect the lock set by another invocation of the same function.

1 Like

Thanks again @Adspectus. I will implement the logging function with the f::append function and closely monitor, if any problems arise.