CodingHowTo

Append to a Log File with Daily Rotation

Append to a Log File with Daily Rotation in PHP

Content

Appending to a log file with daily rotation can be achieved by creating a function in PHP that handles the logging process. This function will check if today's log file already exists and, if not, create it before appending the new log entry.

        <?php
        // Function to log messages with daily rotation
        function logMessage($message) {
            // Get today's date in YYYY-MM-DD format
            $date = date('Y-m-d');
            // Define the log file path with the current date
            $logFile = "logs/{$date}.log";
            
            // Open the log file in append mode
            $fileHandle = fopen($logFile, 'a') or die("Could not open log file.");
            
            // Write the message to the log file
            fwrite($fileHandle, date('Y-m-d H:i:s') . " - {$message}\n");
            
            // Close the log file
            fclose($fileHandle);
        }

        // Example usage of the logMessage function
        logMessage("This is a test log entry.");
        ?>
    

The above code snippet defines a function `logMessage` that takes a message as an argument and appends it to a log file. The log file name includes today's date, ensuring that logs are rotated daily.

Conclusion

Appending log entries with daily rotation in PHP is straightforward and ensures that your application's logs are well-organized. By using the `logMessage` function, you can easily manage and review logs by date, making it easier to troubleshoot and monitor your application.