How to use Custom Logger

As you may know the WordPress Cron base on actions. That means it doesn’t matter if the cron task you want to debug is “yours” or it’s registered by another plugin.

All you need to know is the task action handle. You can easily get this information from Advanced Cron Manager.

 

Adding your action

In your theme’s functions.php or in your plugin you can hook up to the cron task, like this:

add_action( 'cron_task_action_hook', function() {
	// code.	
} );

Because the ACM works only in PHP >=5.3 it’s ok to use anonymous functions here. This is the regular way of handling the Cron task, you can pass there any arguments.

 

Using logger

Now, the logger is in fact just another action where you get special Logger object which saves the log. It looks like this:

add_action( 'advanced-cron-manager/log', function( $logger ) {
	$logger->log( 'Hello World!' );
} );

You can log anything there, even an array. And you want to add that action inside your Cron task callback. This is because it has to be executed only when cron action is executed, not ealier.

 

Complete example

This is how the action with logger should look like. If you wish you can of course pass any variables to the closure, see below:

add_action( 'cron_task_action_hook', function( $arg ) {

	add_action( 'advanced-cron-manager/log', function( $logger ) use ( $arg ) {
		$logger->log( 'This is the argument incremented with 1: ' . ++$arg );
	} );

} );

 

You can also add the logger action to any existing Cron task action, it doesn’t have to be a separate function.

4 people considered this helpful