Every WordPress developer knows how to use WP_DEBUG in the wp-config.php file to enable the WordPress debug log. But how do you go about sending output to the WordPress debug log, so you can debug your own code while developing a theme or plugin?
Every developer is familiar with using the old print_r($my_stuff); die; trick to print the contents of an array (or object) to the screen so you can make sure that your code is doing what you expect. A better way to do this is write to your own custom log file, of course, and until this week I’ve maintained a separate PHP log file and using the PHP error log function to write to this;
error_log($my_stuff, 3, "/var/tmp/my-errors.log");
I then use Console on my mac to watch this log:
While this is completely fine, in the background WordPress is busy sending output to the WordPress debug log file, which (providing you’ve enabled WP_DEBUG) lives in wp-content/debug.log. I got fed up with having two separate Console windows open to monitor these, and looked into how I could write my own output directly to the WordPress debug log. And it turns out it’s pretty easy.
Add the following code to your theme’s functions.php file;
if (!function_exists('write_log')) { function write_log ( $log ) { if ( true === WP_DEBUG ) { if ( is_array( $log ) || is_object( $log ) ) { error_log( print_r( $log, true ) ); } else { error_log( $log ); } } } }
What this does is create a custom logging function that you can call within your code – this first checks to see if WP_DEBUG is set to true (notice the yoda condition here, you will – it’s part of the WordPress coding standards). If WP_DEBUG is switched on, the function prints the contents of $log to the WordPress error log. It doesn’t matter if you’ve populated $log with a variable, array or object – the function checks and handles those.
Whenever you need to be sending output to the WordPress debug log file in your code, simply call the new function as follows;
write_log('THIS IS THE START OF MY CUSTOM DEBUG'); write_log($whatever_you_want_to_log);
Note that I always use two lines here – the first so I can search for my custom output in Console, and the second the actual data I want to log.
Now you can simply monitor the wp-content/debug.log file for both WordPress errors and your custom ones. Hope someone else finds that useful!
Good stuff. Very usefull and your solution is really clean!
Agreed, thanks for this. Exactly what I was looking for.
Glad you both found it useful!
Good stuff, thanks. Maybe save yourself a line with this?
if (!function_exists(‘write_log’)) {
function write_log ( $log ) {
if ( true === WP_DEBUG ) {
error_log(‘THIS IS THE START OF MY CUSTOM DEBUG’);
if ( is_array( $log ) || is_object( $log ) ) {
error_log( print_r( $log, true ) );
} else {
error_log( $log );
}
}
}
}