Skip to content

Custom Logger – a simple auxiliary WordPress plugin for debugging PHP code

  • Code
Custom Logger Log File

I end up adding a version of this to many jobs – virtually all of the ones that involve custom, original PHP coding that I don’t happen to get exactly right the first time. The place where I ran across it originally no longer seems accessbile, and the main addition to it that you won’t necessarily find elsewhere is a “var_export” upon encountering an object to be logged in full.

<?php 
/**
 * Plugin Name: Custom Logger
 * Description: In any PHP file add $message variable or string in format `custom_log( $message ) ;` to print time-coded log in active theme directory; use custom_log() ; just to find out if point in script has been reached; can use as many times as you like in as many different places as you like
 * Author: CK MacLeod
 * Author URI: https://ckmswp.com/ 
 * Version: 1.0
 * Date: June 22, 2020
 */

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
 
if ( ! function_exists( 'custom_log' ) ) {
 
	//just write custom_log() ; if you just want to know if the point is reached
       function custom_log( $message = 'Reached' ) { 

		if ( is_array( $message ) ) { 
			$message = json_encode( $message ) ; 
		} 
		
		if ( is_object( $message ) ) {
			$message = var_export( $message, true ) ;
		}
		 
		$file = fopen(  get_stylesheet_directory() . "/custom_log.log", "a" );  
		fwrite( $file, "\n" . date('Y-m-d h:i:s') . " :: " . $message ) ; 
		fclose( $file ) ; 
		
	}

}
/**
 * GET THE NAME OF THE FUNCTION 
 * BEING LOGGED
 */
if ( function_exists( 'custom_log' ) ) :
function test_logger() {
	
	$message = __FUNCTION__ ;
	
	custom_log( $message ) ;
}
endif;

On a page refresh, will output something like: 2020-06-23 03:29:00 :: test_logger in the custom_log.log file in your active theme’s directory.

Leave a Reply