I recently took over a product stream whose code was approximately two years old. I was shocked to see that it didnít have any logging mechanism in place, which scared the hell out of me. In this article, I'll explain why it scared me, and the best ways to implement logging in PHP applications.
Before we move on to how we can implement logs, let's take a look at what should be the basic design consideration for logs.
File system or database: To store logs, a database as well as a file can be used. The disadvantage with using a database is that the write time is longer, causing an undue load on the database server. The disadvantage with a file system is that the read and searching time is longer than the database server.
The advantage of using a database server is better organization of the logs and better sorting, searching and display capability. So, the rule of thumb is that if the logging is being done excessively, then use a file system to log it; otherwise, you can use a database. Generally, trace logs are more frequently logged, so it would be a good idea to log them to a file system. Audit logs and user logs can be logged to a database.
Priority: There should be an option for logging according to the priority, and this priority should be configurable. Sometimes logging slows the application. In that case, there should be an option of restricting the logs to higher priority issues or stop the application from logging altogether.
Size limit: There should be an option to restrict the total size of the logs, otherwise they may flood the disk (in the worst case). I have seen one application which only had an option to restrict the logs by the number of days -- i.e., you could have logs for 1 day , 2 days ... n days. This application always had this problem in which it would flood the disk with logs and slow the application, because sometimes even when using a one-day window, gigabytes of logs would get created. So there has to be a configurable upper size limit if you're using a file system and a maximum number of rows if you're using a database to contain the total size of logs.
Log file location: The log file location should be configurable, because in some cases you want the log to be in other drives or some location which is other than the install location.
Timestamp: Log messages must contain a timestamp even though they contain the server date time. In some cases you will need to compare the logs of two application instances whose server time could be different from each other.