Utility function for the WordPress error log

There is function for writing information to the WP error log file – error_log().

The problem is that the function doesn’t handle arrays or objects directly. For those, you need to format the data before writing to the log (if you want to be able to read the result in the log).

Here’s a simple utility you can use to pass a string, array, or object and write it to the log without having to worry about pre-formatting the value.

 * Writes string, array, and object data to the WP error log.
 * To use, pass the result to write to the log as follows:
 * write_log( $value_to_write );
 * @param string|array|object $log
function write_log( $log )  {
    if ( is_array( $log ) || is_object( $log ) ) {
        error_log( print_r( $log, true ) );
    } else {
        error_log( $log );

To use this function, just add it to your theme’s functions.php file. Or better yet, add it to your site specific plugin.

You’ll need to make sure that debugging is turned on in your wp-config.php file and that you’ve enabled error logging.

 * The WP debug constants.
 * These are used in wp-config.php to enable debugging.
 * NOTE all of these MUST be inserted in wp-config.php
 * before the following line:
 * /* That's all, stop editing! Happy blogging.

// Turns on general debugging
define( 'WP_DEBUG', true );

 * WP_DEBUG_DISPLAY is optional. If WP_DEBUG is true
 * and WP_DEBUG_DISPLAY is not defined, debugging messages
 * will be output to the screen. So for general debugging
 * it is not needed. But if you need to debug in production
 * and write to the log without displaying to the screen,
 * use the following:
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Enables error logging to /wp-content/debug.log
define( 'WP_DEBUG_LOG', true );

// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );

// Saves the database queries to an array that can help analyze those queries.
define( 'SAVEQUERIES', true );

Leave a comment

Your email address will not be published. Required fields are marked *