Last active
June 25, 2025 23:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } |
Author
Author
Changelog
- Added a
$show_contextparameter (default false): This allows you to toggle whether function, class, and type context is included in the log prefix. - Docblock updated:: It now describes the new parameter and its effect.
- Conditional context logic: The function, class, and type are only added to the log prefix if
$show_contextis true.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changelog
debug_backtrace()to get the file and line number where write_log()was called, so every log entry is prefixed with this info.[file:line]for clarity in the log.