<?php
/**
* Wraps log stream functions with error handling and defensive checks.
*
* @param callable $logFunction The original log function. Must accept a string.
* @param string $logStreamName A descriptive name for the log stream.
* @return callable A wrapped log function.
*/
function wrapLogStream(callable $logFunction, string $logStreamName): callable
{
return function (string $message) use ($logFunction, $logStreamName) {
// Defensive check: Ensure message is a string
if (!is_string($message)) {
throw new InvalidArgumentException("Log message must be a string.");
}
try {
// Perform the logging operation
$logFunction($message);
} catch (Exception $e) {
// Log the error with context
error_log("ERROR: Log stream '$logStreamName' - " . $e->getMessage() . "\n", 3, 'error.log');
// Optionally re-throw the exception, or handle it differently.
// throw $e;
}
};
}
/**
* Example usage: Demonstrates wrapping a hypothetical log function.
*/
function hypotheticalLog(string $message): void
{
// Simulate a logging operation
echo date('Y-m-d H:i:s') . " - " . $message . "\n";
}
// Wrap the hypothetical log function for the data migration log stream.
$migrationLog = wrapLogStream(
'hypotheticalLog',
'data_migration'
);
// Example calls to the wrapped log function:
$migrationLog("Starting data migration process...");
$migrationLog("Successfully processed record: 123");
$migrationLog("ERROR: Failed to process record: 456 - Invalid data");
$migrationLog(123); // This will trigger an exception and be logged.
?>
Add your comment