This is a lightweight way that I like to use to collect log texts in my WordPress plugins across different classes and methods involved in a process. The advantage of this is that it uses WordPress internal functionality, namely the Action API.
To create log messages it uses the do_action function and to collect these messages it uses the add_action function. Therefore it is unnecessary to inject custom logic from an individual logger object into all code parts.
It supports namespaces (what does not mean PHP namespaces) to separate log messages.
The logging logic in one class
This is the class that encapsulates the logging logic:
How to use it
First include the class in your project where you need to collect log messages.
Register log namespace(s)
Then register a namespace for your log messages. You can have several namespaces in parallel.
<?php require_once 'Ifw_Wp_LogCollector.php'; // register log namespace Ifw_Wp_LogCollector::register('my_log_foo'); Ifw_Wp_LogCollector::register('my_other_log'); ?>
Create log messages
Then create log messages with
Ifw_Wp_LogCollector::add('namespace', 'message');
like this:
<?php class MyClass1 { public static function test() { // your code goes here Ifw_Wp_LogCollector::add('my_log_foo', 'some important debug data'); } } class MyClass2 { public static function test() { // your code goes here Ifw_Wp_LogCollector::add('my_log_foo', 'some other important debug data'); } } MyClass1::test(); MyClass2::test();
Flush log / get log messages
Finally you want to get all log messages of a namespace to process them according to your needs, e.g. store them in a file, database or the like.
If you only want to get the interim result, use the method “get“. If you want to reset the log namespace at the same time, for example because you want to clear it within a loop, use the method “end“, which is “get” and “flush” in one.
<?php // get log contents without flushing the namespace $logContents = Ifw_Wp_LogCollector::get('my_log_foo'); // flushing a log namespace manually Ifw_Wp_LogCollector::flush('my_log_foo'); // get and flush in one step $logContents = Ifw_Wp_LogCollector::end('my_log_foo');
Conclusion
This is a small, lightweight, object-oriented method to collect log messages in WordPress plugins or themes without much effort. It does not claim to be perfect and should only be used in appropriate projects. Frameworks often come with their own logging classes, but I find these often oversized for average WordPress projects.
I would be very pleased about feedback and suggestions for improvement.