Logging errors in WooCommerce

Nick

Tracking down errors in PHP can be tricky sometimes, but WordPress and WooCommerce have some built in logging to make it easier. Here are a few snippets for future use:

WP_Debug logs

First, you need to turn on wp_debug and logging in your wp-config.php file. This will create a debug.log file in your wp-content folder, which you can then view errors on. This is how I do that:

// Enable WP_DEBUG mode
define('WP_DEBUG', true);
// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);
// Disable display of errors and warnings
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);

Then, you can output specific variables or functions to that debug log.
Some examples:

  • To view contents of variables, output vars inline in code using
    error_log( 'In ' . __FUNCTION__ . '(), REPLACE_WITH_VARIABLE_NAME = ' . var_export( $REPLACE_WITH_VARIABLE_NAME , true ) );
  • To backtrace which functions are using a function
    error_log( 'In ' . __FUNCTION__ . '(), backtrace = ' . print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), true));

WC Logs

To access the results of the log easily from the dashboard, you can log to a WC logger rather than the error log. You can access error logs by going to WooCommerce > System Status > Logs.

You can then select the error log file you need and click “View”. This will give you any debugging information that you can copy and share, which is super helpful for the support team. Error logs are also located in the /wc-logs folder within your site install.

Example of running a stack trace on a caught exception:
// Log any exceptions to a WC logger
$log = new WC_Logger();
$log_entry = print_r( $e, true );
$log_entry .= 'Exception Trace: ' . print_r( $e->getTraceAsString(), true );
$log->add( 'new-woocommerce-log-name', $log_entry );

Note: this method is updating as of WC 2.7

Starting with WooCommerce 2.7 3.0, logging can be grouped by context and severity. For example:
$logger = wc_get_logger();
$logger->debug( 'debug message', array( 'source' => 'my-extension' ) );

I will try to add to and refine this list as I get more logging tools in my toolbelt.