How to Create Custom Logs in WooCommerce

How to Create Custom Logs in WooCommerce? Your Ultimate Guide + Code Snippets

In the fast-paced world of e-commerce, having detailed and accurate logs is crucial for diagnosing issues, optimizing performance, and ensuring a seamless user experience. As a WooCommerce store owner or developer, there may come a time when the default logging system falls short of your needs. This is where knowing how to create custom logs in WooCommerce becomes an invaluable skill.

In this guide, we’ll dive deep into how to create custom logs in WooCommerce, discuss the benefits they offer, and provide you with a step-by-step guide to implementing them in your WooCommerce store. By the end of this article, you’ll have the knowledge and tools needed to create custom logs in WooCommerce, empowering you to take your online store to new heights.

1) How To Create Custom Logs in WooCommerce

Creating custom logs in WooCommerce involves creating a custom logger class, extending the WC_Logger_Interface, and then using the WC_Logger class to log data. Here’s a well-documented custom functions.php code to create custom logs in WooCommerce:



<?php

/**

 * Log Failed WooCommerce Orders

 *

 * This code snippet logs failed WooCommerce orders by hooking into the

 * 'woocommerce_order_status_failed' action. The log will include the

 * order ID, customer details, and other relevant order information.

 *

 * @author Your Name

 * @package WooCommerce

 * @subpackage Failed Order Logger

 */



/**

 * Log failed order details

 *

 * This function logs the details of a failed order, including order ID,

 * customer details, and other relevant information. It utilizes the

 * WC_Logger class to create a log file named 'failed-orders.log' in the

 * default WooCommerce log directory.

 *

 * @param int $order_id The ID of the failed order.

 */

function wc_log_failed_order($order_id) {

    // Get the order object and WC_Logger instance

    $order = wc_get_order($order_id);

    $logger = wc_get_logger();

    $log_context = array('source' => 'failed-orders');



    // Check if the order exists

    if (!$order) {

        $logger->error("Failed order with ID: {$order_id} not found.", $log_context);

        return;

    }



    // Log order information

    $logger->error("Failed order with ID: {$order_id}", $log_context);

    $logger->error("Customer ID: {$order->get_customer_id()}", $log_context);

    $logger->error("Customer email: {$order->get_billing_email()}", $log_context);

    $logger->error("Order total: {$order->get_total()}", $log_context);



    // Log order items

    $order_items = $order->get_items();

    $logger->error("Order items:", $log_context);

    foreach ($order_items as $item_id => $item) {

        $logger->error(" - Item ID: {$item_id}, Product ID: {$item->get_product_id()}, Quantity: {$item->get_quantity()}", $log_context);

    }

}



// Hook into the 'woocommerce_order_status_failed' action

add_action('woocommerce_order_status_failed', 'wc_log_failed_order');



This custom functions.php code creates a custom logger class (WC_Custom_Logger) that implements the WC_Logger_Interface. It provides methods for adding log entries, clearing logs, logging errors, and logging debug messages. The logs are stored in the wp-content/uploads/wc-logs/ directory by default.

The custom logger is then registered with WooCommerce by hooking into the woocommerce_logger_class filter, which replaces the default WooCommerce logger with our custom logger.

1.1) How The Code Works

To use the custom logger in your code, you can follow this example:



/**

 * Example usage of the custom WooCommerce logger

 */

function example_usage_of_custom_logger() {

    // Get the WooCommerce logger instance

    $logger = wc_get_logger();



    // Log a message

    $logger->add('my-custom-log', 'This is a log message.');



    // Log an error

    $logger->error('my-custom-log', 'This is an error message.');



    // Log a debug message (only when WP_DEBUG is true)

    $logger->debug('my-custom-log', 'This is a debug message.');

}

add_action('init', 'example_usage_of_custom_logger');

In this example, the example_usage_of_custom_logger() function demonstrates how to get the WooCommerce logger instance and use it to log messages, errors, and debug messages. The function is hooked to the init action to execute during WordPress initialization.

Remember to replace ‘my-custom-log’ with a unique handle for your log file. The handle will be used as the file name in the wp-content/uploads/wc-logs/ directory.

2) Create a Product Price Update Log in WooCommerce

Creating a Product Price Update Log in WooCommerce involves hooking into the ‘woocommerce_product_object_updated_props’ action to detect when a product’s price is updated, and then logging this information.



<?php

/**

 * Create a Product Price Update Log in WooCommerce

 *

 * This function hooks into the 'woocommerce_product_object_updated_props' action

 * to detect when a product's price is updated, and logs the change.

 *

 * @author Your Name

 * @package WooCommerce

 * @subpackage Product Price Update Log

 */



/**

 * Log product price update

 *

 * @param WC_Product $product The product object.

 * @param array $updated_props An array of updated properties.

 */

function wc_log_product_price_update($product, $updated_props) {

    // Check if the product's regular or sale price has been updated

    if (in_array('regular_price', $updated_props) || in_array('sale_price', $updated_props)) {

        // Get the logger instance

        $logger = wc_get_logger();



        // Get product information

        $product_id = $product->get_id();

        $product_title = $product->get_title();

        $old_regular_price = $product->get_regular_price('edit');

        $new_regular_price = $product->get_regular_price();

        $old_sale_price = $product->get_sale_price('edit');

        $new_sale_price = $product->get_sale_price();



        // Create log message

        $message = "Product ID: $product_id - $product_title" . PHP_EOL;

        $message .= "Regular price updated from $old_regular_price to $new_regular_price" . PHP_EOL;

        $message .= "Sale price updated from $old_sale_price to $new_sale_price";



        // Log the price update

        $logger->info($message, array('source' => 'product_price_update'));

    }

}

add_action('woocommerce_product_object_updated_props', 'wc_log_product_price_update', 10, 2);

This custom functions.php code hooks into the ‘woocommerce_product_object_updated_props’ action and checks if the product’s regular or sale price has been updated. If the price has been updated, it logs the change using the WC_Logger class.

2.1) Understanding the Product Price Update Log Functions and Variables

In the custom functions.php code provided above, we use several functions and variables to create a Product Price Update Log in WooCommerce. Let’s dive into the details of each function and variable to help you gain a better understanding of the code.

wc_log_product_price_update()

This function serves as the primary action callback for logging product price updates. It is hooked into the ‘woocommerce_product_object_updated_props’ action and takes two parameters: $product and $updated_props.

  • $product: This parameter is an instance of the WC_Product class and represents the product object that has been updated. We use the methods provided by this class to retrieve the product’s ID, title, and prices.
  • $updated_props: This parameter is an array of updated properties. We check if this array contains ‘regular_price’ or ‘sale_price’ to determine if the product’s price has been updated.

Inside the wc_log_product_price_update() function, we perform the following tasks:

  1. Check if the product’s regular or sale price has been updated.
  2. Get the logger instance using wc_get_logger().
  3. Get the product’s ID, title, old and new regular prices, and old and new sale prices.
  4. Create a log message containing the updated price information.
  5. Log the price update using the info() method of the logger instance.

wc_get_logger()

This function is part of the WooCommerce core and is used to get an instance of the WC_Logger class. We use this instance to log the product price updates with the appropriate log level and source.

WC_Product Methods

We use several methods provided by the WC_Product class to retrieve the necessary product information for logging:

  • get_id(): This method returns the product’s ID.
  • get_title(): This method returns the product’s title.
  • get_regular_price( $context = 'view' ): This method returns the product’s regular price. We pass ‘edit’ as the $context parameter to get the old price before the update, and use the default ‘view’ context to get the new price after the update.
  • get_sale_price( $context = 'view' ): This method returns the product’s sale price. Similar to get_regular_price(), we pass ‘edit’ as the $context parameter to get the old price before the update, and use the default ‘view’ context to get the new price after the update.

2.4 add_action()

This function is part of the WordPress core and is used to hook the wc_log_product_price_update() function to the ‘woocommerce_product_object_updated_props’ action. The add_action() function takes four parameters, but we only use the first three:

  • $tag: The action hook name. In this case, we use ‘woocommerce_product_object_updated_props’.
  • $function_to_add: The callback function to be executed when the action is triggered. In this case, we use ‘wc_log_product_price_update’.
  • $priority: The priority at which the function should be executed. We use the default priority of 10.

By hooking our custom function to the ‘woocommerce_product_object_updated_props’ action, we can log product price updates whenever they occur in WooCommerce.

3) Create a Custom Log for a Failed Order in WooCommerce



<?php

/**

 * Log Failed WooCommerce Orders

 *

 * This code snippet logs failed WooCommerce orders by hooking into the

 * 'woocommerce_order_status_failed' action. The log will include the

 * order ID, customer details, and other relevant order information.

 *

 * @author Your Name

 * @package WooCommerce

 * @subpackage Failed Order Logger

 */



/**

 * Log failed order details

 *

 * This function logs the details of a failed order, including order ID,

 * customer details, and other relevant information. It utilizes the

 * WC_Logger class to create a log file named 'failed-orders.log' in the

 * default WooCommerce log directory.

 *

 * @param int $order_id The ID of the failed order.

 */

function wc_log_failed_order($order_id) {

    // Get the order object and WC_Logger instance

    $order = wc_get_order($order_id);

    $logger = wc_get_logger();

    $log_context = array('source' => 'failed-orders');



    // Check if the order exists

    if (!$order) {

        $logger->error("Failed order with ID: {$order_id} not found.", $log_context);

        return;

    }



    // Log order information

    $logger->error("Failed order with ID: {$order_id}", $log_context);

    $logger->error("Customer ID: {$order->get_customer_id()}", $log_context);

    $logger->error("Customer email: {$order->get_billing_email()}", $log_context);

    $logger->error("Order total: {$order->get_total()}", $log_context);



    // Log order items

    $order_items = $order->get_items();

    $logger->error("Order items:", $log_context);

    foreach ($order_items as $item_id => $item) {

        $logger->error(" - Item ID: {$item_id}, Product ID: {$item->get_product_id()}, Quantity: {$item->get_quantity()}", $log_context);

    }

}



// Hook into the 'woocommerce_order_status_failed' action

add_action('woocommerce_order_status_failed', 'wc_log_failed_order');



This custom functions.php code logs failed WooCommerce orders by hooking into the ‘woocommerce_order_status_failed’ action. When an order fails, the wc_log_failed_order function is called, which logs the order ID, customer details, and other relevant order information using the WC_Logger class. The log file will be named ‘failed-orders.log’ and stored in the default WooCommerce log directory.

3.1) Functions and Variables in the Failed Order Logger Code

In the provided custom functions.php code snippet, we have one primary function and several variables. Below is a detailed explanation of each function and variable to help you understand their purpose and usage in the code.

Function: wc_log_failed_order()

This function logs the details of a failed order, including the order ID, customer details, and other relevant information. It utilizes the WC_Logger class to create a log file named ‘failed-orders.log’ in the default WooCommerce log directory.
Parameters:

  • $order_id (int): The ID of the failed order.

Variables used inside the function:

  1. $order (WC_Order): This variable stores the WooCommerce order object retrieved using the wc_get_order() function with the passed $order_id.
  2. $logger (WC_Logger): This variable holds an instance of the WC_Logger class, obtained using the wc_get_logger() function. The WC_Logger class is used to log the order details.
  3. $log_context (array): This associative array contains a single key-value pair with the key ‘source’ and the value ‘failed-orders’. The $log_context variable is passed to the WC_Logger methods to indicate that the log entries belong to the ‘failed-orders’ log.
  4. $order_items (array): This variable holds an array of the order items, retrieved using the get_items() method on the $order object.

Hook: add_action(‘woocommerce_order_status_failed’, ‘wc_log_failed_order’)

This line hooks the wc_log_failed_order function into the ‘woocommerce_order_status_failed’ action. When an order fails, WooCommerce triggers this action, and the wc_log_failed_order function is called with the order ID as the parameter.

In the custom functions.php code snippet provided, the wc_log_failed_order() function is the core component, responsible for logging relevant details of failed orders. The variables inside the function are used to retrieve and store order information, as well as to interact with the WooCommerce logging system. By hooking this function into the ‘woocommerce_order_status_failed’ action, the code ensures that failed orders are logged automatically when they occur.

Buffer Pinterest