Logging is a crucial aspect of WordPress development, especially when debugging and tracking issues. In this guide, we’ll show you how to implement a custom write_log() function in WordPress using error_log(), which allows you to log different types of messages (information, warnings, errors, and more).
Creating the Custom write_log() Function
The custom write_log() function leverages the built-in error_log() function to log various messages during development. This helps you track and resolve issues efficiently.
function write_log($message) {
if (true === WP_DEBUG) {
if (is_array($message) || is_object($message)) {
error_log(print_r($message, true));
} else {
error_log($message);
}
}
}
How It Works
Here’s a breakdown of the function:
- WP_DEBUG Check: Ensures the log messages are only written when WordPress debugging is enabled (set to
true) inwp-config.php. - Array/Object Logging: If the message is an array or object, it converts it into a readable string format using
print_r(). - Scalar Logging: If it’s a simple data type (e.g., string, integer, etc.), it logs the message directly.
Usage Example
You can use the write_log() function anywhere in your WordPress code to log messages for debugging:
function my_custom_function() {
$data = array('foo' => 'bar', 'hello' => 'world');
write_log('My custom message.');
write_log($data);
}
Viewing the Log Messages
Make sure to enable debugging by adding the following lines in your wp-config.php file:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
Once enabled, WordPress will log the messages into an error log file, which can typically be found in your server’s error log directory. If you want to specify a custom log file, you can modify the error_log directive in php.ini.
Best Practices for Debugging in WordPress
When using logging in WordPress, follow these best practices:
- Always disable debugging on production sites by setting
WP_DEBUGtofalse. - Use logging only for non-sensitive data to avoid exposing any personal information.
- Regularly clear your log files to avoid storing unnecessary data.
Related Resources
For further reading, here are some useful external links:
By using this custom logging technique, you’ll be able to easily monitor your WordPress site and troubleshoot issues effectively during development.
