What are some best practices for implementing a custom logging system in PHP to track user activities, such as failed login attempts, and ensure data security and integrity?

To implement a custom logging system in PHP to track user activities like failed login attempts, it is essential to create a secure and efficient solution. One way to achieve this is by creating a separate log file for each type of activity, such as login attempts, and ensuring that sensitive information is not logged in plaintext. Additionally, consider implementing log rotation to manage log file sizes and prevent them from becoming too large.

<?php

// Function to log user activities
function logActivity($activity, $username) {
    $logFile = 'activity_log_' . $activity . '.txt';
    $logMessage = "[" . date('Y-m-d H:i:s') . "] User " . $username . " attempted " . $activity . "\n";
    
    // Ensure log directory exists and is writable
    if (!is_dir('logs')) {
        mkdir('logs');
    }
    
    // Write log message to file
    file_put_contents('logs/' . $logFile, $logMessage, FILE_APPEND);
}

// Example usage
$username = 'john_doe';
logActivity('login_attempt', $username);
?>