Skip to content

Instantly share code, notes, and snippets.

@addzycullen
Last active June 25, 2025 23:02
Show Gist options
  • Select an option

  • Save addzycullen/b7f59d14960686217289d5c9a1812801 to your computer and use it in GitHub Desktop.

Select an option

Save addzycullen/b7f59d14960686217289d5c9a1812801 to your computer and use it in GitHub Desktop.
This fn allows you write to the WordPress debug log if you have it enabled in the wp_config file.
if (!function_exists('write_log')) {
/**
* Write to Debug Log with Optional Context
*
* Logs the provided variable to the PHP error log, always prefixed with the file and line number.
* Optionally includes function, class, and call type context if $show_context is true.
*
* @param mixed $log The content to log (string, array, object, etc).
* @param bool $show_context Whether to include function, class, and type context. Default false.
* @return void
*/
function write_log($log, $show_context = false)
{
// Get the backtrace to find the caller's context
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$caller = isset($backtrace[1]) ? $backtrace[1] : (isset($backtrace[0]) ? $backtrace[0] : []);
$file = isset($caller['file']) ? $caller['file'] : 'unknown file';
$line = isset($caller['line']) ? $caller['line'] : 'unknown line';
// Always include file and line in the prefix
$context = "[{$file}:{$line}] ";
// Optionally add function, class, and type context
if ($show_context) {
$function = isset($caller['function']) ? $caller['function'] : 'global scope';
$class = isset($caller['class']) ? $caller['class'] : '';
$type = isset($caller['type']) ? $caller['type'] : '';
if ($class) {
$context .= "{$class}{$type}";
}
$context .= "{$function}() - ";
}
// Format the log message
if (is_array($log) || is_object($log)) {
$message = $context . print_r($log, true);
} else {
$message = $context . $log;
}
// Write to the error log
error_log($message, 0);
}
}
@addzycullen
Copy link
Copy Markdown
Author

Changelog

  1. Backtrace for File and Line: Used ‎debug_backtrace() to get the file and line number where ‎write_log() was called, so every log entry is prefixed with this info.
  2. Prefix Construction: Built a prefix string in the format ‎[file:line] for clarity in the log.
  3. Docblock Update: Updated the Docblock to reflect the new behaviour and clarify the parameter type.

@addzycullen
Copy link
Copy Markdown
Author

Changelog

  1. Added a ‎$show_context parameter (default ‎false): This allows you to toggle whether function, class, and type context is included in the log prefix.
  2. Docblock updated:: It now describes the new parameter and its effect.
  3. Conditional context logic: The function, class, and type are only added to the log prefix if ‎$show_context is ‎true.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment