What are best practices for handling errors and logging when working with SSH connections in PHP?

When working with SSH connections in PHP, it is important to handle errors gracefully and log any relevant information for troubleshooting purposes. One best practice is to use try-catch blocks to catch exceptions that may occur during SSH operations and log the error messages to a file or output them to the console.

<?php
use phpseclib\Net\SSH2;

// Create SSH connection
$ssh = new SSH2('example.com');

try {
    if (!$ssh->login('username', 'password')) {
        throw new Exception('Login failed');
    }

    // Perform SSH operations here

} catch (Exception $e) {
    // Log error message to a file
    file_put_contents('ssh_errors.log', '[' . date('Y-m-d H:i:s') . '] ' . $e->getMessage() . PHP_EOL, FILE_APPEND);

    // Output error message to the console
    echo 'Error: ' . $e->getMessage();
}
?>