Adding Your Own Debugging Information to debug.log

November 4, 2015
Posted in: Code Snippets, Web Development, WordPress

We’ve all been there – you’re developing away and everything is sunshine and rainbows when all of a sudden, things stop working and you don’t know why. You open the PHP error_log, but it’s empty. The next step is to start debugging line-by-line, and output variables and messages along the way.

Instead of outputting each message to the page, potentially causing a visual mess, you can easily send them to a file with the help of the WP_DEBUG constant in wp-config.php.

Two things need to be done to make this happen:

1) Enable WP_DEBUG and send all messages to the log file.

In wp-config.php, find this line:


define('WP_DEBUG', false);

And change it to this:


define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', false);
define('WP_DEBUG_LOG', true);

This will enable debugging, but will hide them from users, and send them to wp-content/debug.log.

2) Create a function to add your own messages to debug.log

Add this code to your theme’s functions.php file:


if (!function_exists('write_log')) {
    function write_log ( $log )  {
        if ( true === WP_DEBUG ) {
            $backtrace = debug_backtrace();
            $caller = $backtrace[0]['file'] . ":" . $backtrace[0]['line']  ;
            error_log('Caller: ' . $caller);
            if ( is_array( $log ) || is_object( $log ) ) {
                error_log( print_r( $log, true ) );
            } else {
                error_log( $log );
            }
        }
    }
}

To add your own debugging messages to debug.log, you can simply call write_log() as follows:


// strings
write_log( 'A sample debug message' );

// variables
write_log( $message );

You’ll then see two lines added to debug.log – one that outlines the file and line number where you called the function, and one that includes the message itself.

Happy debugging!

Scott Buckingham

President / Owner
613-801-1350 x101
[email protected]
Scott is a WordPress expert who has worked on hundreds of web design and development projects. He excels at finding creative ways to solve technical problems. View full profile