Skip to content

Instantly share code, notes, and snippets.

@n18l
Created March 31, 2020 22:07
Show Gist options
  • Save n18l/b7266786f3d31da36a1e3f2718a71690 to your computer and use it in GitHub Desktop.
Save n18l/b7266786f3d31da36a1e3f2718a71690 to your computer and use it in GitHub Desktop.
Readable logging for PHP
/**
* Writes a formatted line to the current environment's error log.
*
* @param mixed... $items_to_log One or more items to output to the log.
*
* @since 2020.2.0
* @author Nick Brombal <nick.brombal@publicishawkeye.com>
*/
function debug_log(...$items_to_log): void
{
// Get the context for where the logging function was called.
$log_context = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
// Define an intro line for logs written with this function.
$log_intro = "Logged output from {$log_context['file']}:{$log_context['line']}:" . CRLF;
// Initialize the log contents.
$log_content = '';
foreach ($items_to_log as $item_index => $item_to_log) {
// Add spaces between subsequent log items.
if ($item_index > 0) {
$log_content .= ' ';
}
// Append this item to the contents of the output, formatted as a
// parsable string.
$log_content .= var_export($item_to_log, true);
}
// Write to the log.
error_log($log_intro . $log_content);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment