How to log information, warnings, errors In wordpress

To create a custom `write_log()` function for WordPress, you can use the `error_log()` function to write messages to the error log. This function will allow you to log information, warnings, errors, or any other messages during development or debugging.

Here’s a simple implementation of the `write_log()` function:

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);
        }
    }
}

 

Explanation:

1. The function checks if `WP_DEBUG` is set to `true`. This ensures that the log messages will only be written when debugging is enabled in your WordPress configuration. It’s a standard practice to log messages only in the development environment.

2. If the `$message` passed to the function is an array or an object, it uses `print_r()` to convert it to a string representation before logging it. This way, you can log complex data structures for better debugging.

3. If the `$message` is a scalar value (string, integer, float, etc.), it directly logs it using `error_log()`.

Usage:

You can use the `write_log()` function anywhere in your WordPress code to log messages. For example:

function my_custom_function() {
    $data = array('foo' => 'bar', 'hello' => 'world');
    write_log('My custom message.');
    write_log($data);
}

 

Remember to call `my_custom_function()` while `WP_DEBUG` is set to `true` in your `wp-config.php` file.

To view the log messages, you can access the error log file of your web server. The location of the error log file depends on the server configuration. For example, in Apache, it’s often found in the server’s error log directory. In PHP configurations, you can also set a custom log file by modifying the `error_log` directive in `php.ini`.

Related Blogs

How To Limit Search To Only Post Titles?

I added a text field to the posts filter form and I use s= parameter to make the search work. But how to search only in the title of the post (not in the content)? how to limit search to post titles? How to search only by Post Title?

Add Custom Taxonomy Filter on Products Dashboard.

How To Filter Products by Taxonomies in the Dashboard?

WooCommerce provide Many Product filters on admin screen , such as “Select a category”, “Filter by product type”, “Filter by stock status”.

Request A Quote

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.