Whenever I’m working on a project, I often have WordPress set in debug mode, and I like to write messages to the error log that I can easily view, trace, and follow whenever I’m working on a project.

WordPress Debug Log: Monolog

When I do this, there are two ways (and it just depends on the project):

  • I’ll use a library such as Monolog,
  • I’ll use my own, simple log function.

In this post, I’m going to cover the latter. That is, I’m going to share how I write messages to the WordPress debug log and then some of the things you may need to pay attention to whenever you’re doing the same.

The WordPress Debug Log

First, it’s important to note that the function I’m going to share is usually in the context of a base class.

Let’s say I have an AbstractSubscriber all of my subscribers implement (such as a ScriptAssetSubscriber for registering and enqueuing JavaScript file).

The AbstractSubscriber will include this function so it can be called by any child classes. The function is quite simple:

But there are several things about this function that may violate a principle or trigger errors in code quality tools.

Optional Boolean Arguments

Whenever a function accepts an optional boolean argument, it may indicate that a function has more than one responsibility (thus violating the Single Responsibility Principle).

WordPress Debug Log: SRP

The reason this would violate said principle is that it gives a module more than one reason to change.

I’m comfortable allowing this to be written this way because I use it for debugging, not for production environments, and because there are times where I may want to execution to halt, and there are times I don’t.

And sure, I could write two separate functions, but if this is the only function doing this, I’m okay with that.

Forbidden Exit Statements

Other code quality tools dislike the exit statement (and, similarly, they dislike the die statement). And understandably so: They typically bring the program to a complete halt when we should be throwing an exception, returning a value, or generally doing something to handle the situation gracefully.

Again, though, because in this function there are times where I want to stop the execution, I’m okay dealing with the consequences of having the line of code in the function.

Alternatively, I could use wp_die(), and most code quality tools wouldn’t likely catch it, but that’s masking the main issue. If anything, perhaps it’s best just to suppress the warning using whatever directive your sniffer of choice may allow.

Regardless, Log The Message

Ultimately, the purpose of the function above is to provide a simple way to write to the WordPress debug log and optionally stop the execution of the program when doing so.

Understanding WordPress Error Logs: Writing to the Log

It’s clearly not without its problems, and there are higher quality libraries that are available, but sometimes you don’t need a sledgehammer for a problem thumbtack.