How to collect log messages across multiple classes or functions in WordPress plugins or themes.

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.

Create log messages

Then create log messages with

like this:

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.

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.

 

No comments yet.

Leave a Reply

5 × 2 =