Why is the list of log handlers in WooCommerce an array?
This is going to be as much a help for me, as, I hope, it will be for you.
So WooCommerce 2.7 3.0.0 introduced a new way to handle logs, which is brilliant. There are two pieces to it:
- the logger class itself, and
- the log handler
Basically the default logger class (WC_Logger
) passes everything to the handler. When I say everything, I mean no matter which method is being called, it will call $logger->log
internally, which calls $handler->handle( $timestamp, $level, $message, $context )
.
The default handler is a file logger, which ends up working the same as before.
For my use case, I want the logs to end up somewhere different than in a log file on the server, so all I have to do is replace the log handler.
This is how the logger decides what the handlers are going to be:
And this is how it's decided which handler to use:
Documentation says that we should put the following code in the wp-config.php
file:
define( 'WC_LOG_HANDLER', 'WC_Log_Handler_DB' );
I find that problematic, because editing wp-config.php
isn’t exactly plugin territory, so let’s not do that.
Also we could just hook into the same filter, and then start with an empty array, but the question is:
Why is that an array to begin with?
So in WC_Logger
every request will end up in the log
method. This is that:
Which means the reason it’s an array because the same log message can be handled multiple times, for example:
- written to a file
- AND send a text message if severity is serious enough
- AND sent to a remote server
- AND sent to an sIoT (s for secure) device that turns on a red flashing light in the office
If it was just a string, you’d have only one way to handle a log, and that might be insufficient.
Also you might want to set the logger threshold to null
, or not set it at all. That will mean that WooCommerce’s default logger will handle all of the log messages, which means all messages, regardless of severity, will be passed to all handlers to handle.
In your handlers you can still just discard logs that don’t reach the severity. For example if you have Twilio, you can have alerts sent to your phone if the logs are emergency
, alert
, critical
, or error
levels, but you can just not do anything if the logs are below that.
Today I learned. And hopefully you too. :)
Happy Easter, folks!