1. <?php
  2. /**
  3. * Wraps log stream functions with error handling and defensive checks.
  4. *
  5. * @param callable $logFunction The original log function. Must accept a string.
  6. * @param string $logStreamName A descriptive name for the log stream.
  7. * @return callable A wrapped log function.
  8. */
  9. function wrapLogStream(callable $logFunction, string $logStreamName): callable
  10. {
  11. return function (string $message) use ($logFunction, $logStreamName) {
  12. // Defensive check: Ensure message is a string
  13. if (!is_string($message)) {
  14. throw new InvalidArgumentException("Log message must be a string.");
  15. }
  16. try {
  17. // Perform the logging operation
  18. $logFunction($message);
  19. } catch (Exception $e) {
  20. // Log the error with context
  21. error_log("ERROR: Log stream '$logStreamName' - " . $e->getMessage() . "\n", 3, 'error.log');
  22. // Optionally re-throw the exception, or handle it differently.
  23. // throw $e;
  24. }
  25. };
  26. }
  27. /**
  28. * Example usage: Demonstrates wrapping a hypothetical log function.
  29. */
  30. function hypotheticalLog(string $message): void
  31. {
  32. // Simulate a logging operation
  33. echo date('Y-m-d H:i:s') . " - " . $message . "\n";
  34. }
  35. // Wrap the hypothetical log function for the data migration log stream.
  36. $migrationLog = wrapLogStream(
  37. 'hypotheticalLog',
  38. 'data_migration'
  39. );
  40. // Example calls to the wrapped log function:
  41. $migrationLog("Starting data migration process...");
  42. $migrationLog("Successfully processed record: 123");
  43. $migrationLog("ERROR: Failed to process record: 456 - Invalid data");
  44. $migrationLog(123); // This will trigger an exception and be logged.
  45. ?>

Add your comment