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:
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
// Enable Debug logging to the /wp-content/debug.log file
// Disable display of errors and warnings
Then, you can output specific variables or functions to that debug log.
- 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));
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.